1

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 ?

Narendra
  • 151
  • 1
  • 12
  • 2
    you can use terminal function - min/max with your comparator. Take a look at [this one](https://stackoverflow.com/questions/22561614/java-8-streams-min-and-max-why-does-this-compile#) – Gurwinder Singh Oct 24 '17 at 14:29
  • 2
    could you pls paste here what you have tried? – Vaseph Oct 24 '17 at 14:32

2 Answers2

2

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));
1

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()
gnzlrm
  • 190
  • 1
  • 12