Search code examples
javalambdapredicatefunctional-interface

Java 8 Predicate to select an element from list based on element properties


There is a List Employee Objects, each employee object has property start date. Task is to select only one employee who has the earliest start date. I am trying to use Java 8 Predicate for this. So basically how can I compare list elements with each other in predicate ? And how can I do the same thing using lambda with Functional interface ?


Solution

  • Java Predicates are based on the mathematical concept of a Predicate, which is a function F(x) that returns true or false based on some properties of x. Given that the function cannot be redefined while traversing the collection, it isn't probably the to-go option for finding the minimum or maximum of some Collection.

    A recommended way of doing so using Java 8 would be using the min function included on Java Streams.

    Employee oldestEmployee = employees.stream().min(Comparator.comparing(Employee::getStartDate)).get()