猿问

在 Java 8 中基于属性和谓词删除重复项

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


给定具有ID,姓名和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));

我想输出:


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

因此,根据员工的id属性从列表中删除重复项,并出于明显的原因选择IQ最高的员工。:)


特别是,我有兴趣调整这个解决方案,该解决方案仅基于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));

有没有办法?


慕姐4208626
浏览 76回答 1
1回答

温温酱

怎么样,Collection<Employee>&nbsp;distinctEmps&nbsp;=&nbsp;employee.stream() &nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toMap(Employee::getId,&nbsp;Function.identity(),&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(e1,&nbsp;e2)&nbsp;->&nbsp;e1.getIq()&nbsp;>=&nbsp;e2.getIq()&nbsp;?&nbsp;e1&nbsp;:&nbsp;e2)) &nbsp;&nbsp;&nbsp;&nbsp;.values();仅仅遵循@Holgers方法的另一种变体是,Collection<Employee>&nbsp;distinctEmps&nbsp;=&nbsp;employee.stream() &nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toMap(Employee::getId,&nbsp;Function.identity(),&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;BinaryOperator.maxBy(Comparator.comparing(Employee::getIq)))) &nbsp;&nbsp;&nbsp;&nbsp;.values();
随时随地看视频慕课网APP

相关分类

Java
我要回答