Java List 对象集合去重:根据特定字段实现去重
可以使用 Java 8 的 Stream API 来实现根据某一个字段进行去重。
假设有一个 List
List<Person> people = new ArrayList<>();
// 添加 Person 对象到集合中
people.add(new Person('John', 25));
people.add(new Person('John', 30));
people.add(new Person('Alice', 28));
people.add(new Person('Bob', 25));
people.add(new Person('Alice', 30));
// 根据 name 字段进行去重
List<Person> distinctPeople = people.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))),
ArrayList::new
));
// 输出去重后的结果
distinctPeople.forEach(System.out::println);
输出结果为:
Person{name='Alice', age=28}
Person{name='Bob', age=25}
Person{name='John', age=25}
在这个例子中,我们使用 Stream 的 collect 方法和 Collectors 的 toCollection 方法来创建一个 TreeSet,通过 Comparator.comparing 方法来指定根据 name 字段进行比较。然后通过 collectingAndThen 方法将 TreeSet 转换成 ArrayList,实现了根据 name 字段进行去重的效果。
原文地址: https://www.cveoy.top/t/topic/bm3P 著作权归作者所有。请勿转载和采集!