基于 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));
有没有办法?
温温酱
相关分类