Java 8 : Lambda expression with where condition

Viewed 716

Let's say I have below records in a table in DB.

Empl table

Here Emplid and date combination is my PK. With every change I maintain version of records. (in last 3 rows there are total 3 version as change in number).

Now I want to fetch record where emplid = 1111 date = 28-02-2019 with latest version (user don't know how many version are there in db).

How can I do it with lambda expression.

HrcKey matchedKey = hrcKeyList.stream()
             .filter(x -> (currEmplid.equals(x.getEmplid()) && 
                     format.format(updateListFromUI.getDate())
                                  .equals(format.format(x.getDate()))))
             .findFirst()
             .orElse(null);

this will give me vesrion 1. but how can I get latest version.

3 Answers

You can use max to get latest object by comparing version value.

hrcRestatementKeyList.stream()
            .filter(x -> (currEmplid.equals(x.getEmplid()) &&
                    format.format(updatedHrcDbpRestatement.getExtr_effdt())
                            .equals(format.format(x.getExtr_effdt()))))
            .max(Comparator.comparingInt(HrcRestatementKey::getVersion))
            .orElse(null);

in short you can do something like this,

employees.stream().
                filter(hrc -> hrc.empid == 11 && hrc.date.equals("28-02-2000")).
                min((o1, o2) -> o2.version - o1.version).orElse(null);

full example,

public static void main(String[] args) {
        RnD rnD = new RnD();
        rnD.test();
    }
    private void test() {
        List<Hrc> employees = new ArrayList<>();
        employees.add(new Hrc(11, "28-02-2000", 1));
        employees.add(new Hrc(11, "28-02-2000", 2));
        employees.add(new Hrc(11, "28-02-2000", 3));
        employees.add(new Hrc(11, "30-02-2000", 1));
        employees.add(new Hrc(22, "11-02-2000", 1));
        Hrc topVersion= employees.stream().
                filter(hrc -> hrc.empid == 11 && hrc.date.equals("28-02-2000")).
                min((o1, o2) -> o2.version - o1.version).orElse(null);
        System.out.println(topVersion);
    }
    private static class Hrc {
        int empid;
        String date;
        int version;

        public Hrc(int empid, String date, int version) {
            this.empid = empid;
            this.date = date;
            this.version = version;
        }

        @Override
        public String toString() {
            return "Hrc{" +
                    "empid=" + empid +
                    ", date='" + date + '\'' +
                    ", version=" + version +
                    '}';
        }
    }

I'd go with this code snippet:

yourList.stream()
        .filter(x -> currEmplid.equals(x.getEmplid())
        .filter(x -> updatedHrcDbpRestatement.getExtr_effdt()
                                             .equals(x.getExtr_effdt())
        .max(comparingInt(HrcRestatementKey::getVersion))
        .orElse(null);
Related