基于 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));有没有办法?
1 回答
温温酱
TA贡献1752条经验 获得超4个赞
怎么样,
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();
添加回答
举报
0/150
提交
取消