Question based on https://stackoverflow.com/a/29671501/2517622
Given a list of employees with id, name and IQ:
List<Employee> employee = Arrays.asList(new Employee(1, "John", 80), new Employee(1, "Bob", 120), Employee(1, "Roy", 60), new Employee(2, "Alice", 100));
I want to output:
[Employee{id=1, name='Bob', iq=120}, Employee{id=2, name='Alice', iq=100}]
So, remove duplicates from the list based on id property of employee and choose employee with the highest IQ for obvious reasons. :)
Particularly, I am interested in adjusting this solution which removes duplicates only based on id:
import static java.util.Comparator.comparingInt;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
...
List<Employee> unique = employee.stream()
.collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingInt(Employee::getId))),
ArrayList::new));
Is there a way?