您的位置:首页 >Java Stream 去重保留首元素方法
发布于2026-04-20 阅读(0)
扫一扫,手机访问

本文详解如何利用 Java 8+ Stream API 实现按对象某一属性(如城市)分组后,从每组中选取首个对象构成新列表,涵盖标准写法、自定义工具方法及关键注意事项。
本文详解如何利用 Java 8+ Stream API 实现按对象某一属性(如城市)分组后,从每组中选取首个对象构成新列表,涵盖标准写法、自定义工具方法及关键注意事项。
在实际开发中,常需对集合进行“按某字段分组 + 每组取一”的操作,例如:从一批 Person 对象中,为每个 city 仅保留一人(如第一个出现的)。Java Stream 本身不提供直接的 distinctByKey 原生支持,但可通过组合 Collectors.groupingBy 与后续映射高效实现。
最清晰、可读性强且符合函数式风格的做法是先按目标字段分组为 Map<K, List<V>>,再遍历 Entry 并取每组 List 的首个元素:
import java.util.*;
import java.util.stream.Collectors;
List<Person> people = Arrays.asList(
new Person("New York", "foo", "bar"),
new Person("New York", "bar", "foo"),
new Person("New Jersey", "foo", "bar"),
new Person("New Jersey", "bar", "foo")
);
List<Person> firstByCity = people.stream()
.collect(Collectors.groupingBy(Person::getCity))
.values().stream()
.map(list -> list.get(0)) // 取每组第一个 Person
.collect(Collectors.toList());
System.out.println(firstByCity);
// 输出: [{ city: New York, firstName: foo, lastName: bar },
// { city: New Jersey, firstName: foo, lastName: bar }]? 说明:Collectors.groupingBy(Person::getCity) 返回 Map<String, List<Person>>,其 values() 是所有分组列表的集合;后续流对每个 List<Person> 调用 get(0) 即得各城市的首个代表。
若需复用或支持更灵活的值提取(如只取姓名、转换为 DTO),可封装泛型工具方法:
public static <E, K, V> Map<K, List<V>> groupBy(
Collection<E> collection,
Function<E, K> keyFn,
Function<E, V> valueFn) {
return collection.stream()
.map(item -> new AbstractMap.SimpleEntry<>(
keyFn.apply(item), valueFn.apply(item)))
.collect(Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
}
public static <E, K> Map<K, List<E>> groupBy(
Collection<E> collection,
Function<E, K> keyFn) {
return groupBy(collection, keyFn, Function.identity());
}调用示例(等价于上例,但更具扩展性):
List<Person> firstByCity = groupBy(people, Person::getCity)
.values().stream()
.map(list -> list.get(0))
.collect(Collectors.toList());List<Person> firstByCity = new ArrayList<>(people.stream()
.collect(Collectors.toMap(
Person::getCity,
Function.identity(),
(existing, replacement) -> existing // 保留第一个
)).values());按属性获取每组首个对象的核心在于「分组 → 提取首项」两步流水线。推荐优先采用 groupingBy + values().stream().map(...get(0)) 组合,逻辑直观、易于维护;必要时再通过泛型工具方法提升复用性。始终关注空值与顺序保障,即可稳健应对各类业务去重场景。
上一篇:腾讯会议入口及官网使用教程
下一篇:悟空浏览器沉浸模式开启方法
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9