Reputation: 161
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 ?
Upvotes: 1
Views: 1278
Reputation: 302
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()
Upvotes: 1
Reputation: 186
Supposing you have Employee:
class Employee {
private LocalDate startDate;
}
Constructor and getter are omitted. You can find the employee with the earliest startDate as follows:
Optional<Employee> min = list.stream()
.min(Comparator.comparing(Employee::getStartDate));
Upvotes: 2