根据属性和Java 8中的谓词删除重复项

时间:2019-03-28 15:21:08

标签: java java-8

基于https://stackoverflow.com/a/29671501/2517622的问题

给出具有ID,姓名和智商的员工列表:

List<Employee> employee = Arrays.asList(new Employee(1, "John", 80), new Employee(1, "Bob", 120), Employee(1, "Roy", 60), new Employee(2, "Alice", 100));

我要输出:

[Employee{id=1, name='Bob', iq=120}, Employee{id=2, name='Alice', iq=100}]

因此,出于显而易见的原因,请根据雇员的id属性从列表中删除重复项,并选择智商最高的雇员。 :)

特别是,我有兴趣调整此解决方案,该解决方案仅根据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));

有办法吗?

1 个答案:

答案 0 :(得分:8)

怎么样,

Collection<Employee> distinctEmps = employee.stream()
    .collect(Collectors.toMap(Employee::getId, Function.identity(), 
        (e1, e2) -> e1.getIq() >= e2.getIq() ? e1 : e2))
    .values();

仅遵循@Holgers方法的另一个变体是

Collection<Employee> distinctEmps = employee.stream()
    .collect(Collectors.toMap(Employee::getId, Function.identity(), 
        BinaryOperator.maxBy(Comparator.comparing(Employee::getIq))))
    .values();