
本文详解如何利用 java 8+ stream api 实现按对象某一属性(如城市)分组后,从每组中选取首个对象构成新列表,涵盖标准写法、自定义工具方法及关键注意事项。
本文详解如何利用 java 8+ stream api 实现按对象某一属性(如城市)分组后,从每组中选取首个对象构成新列表,涵盖标准写法、自定义工具方法及关键注意事项。
在实际开发中,常需对集合进行“按某字段分组 + 每组取一”的操作,例如:从一批 Person 对象中,为每个 city 仅保留一人(如第一个出现的)。Java Stream 本身不提供直接的 distinctByKey 原生支持,但可通过组合 Collectors.groupingBy 与后续映射高效实现。
✅ 推荐方案:groupingBy + entrySet().stream() 提取首元素
最清晰、可读性强且符合函数式风格的做法是先按目标字段分组为 Map
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
>,其 values() 是所有分组列表的集合;后续流对每个 List 调用 get(0) 即得各城市的首个代表。
? 进阶封装:通用分组工具方法(支持自定义值映射)
若需复用或支持更灵活的值提取(如只取姓名、转换为 DTO),可封装泛型工具方法:
立即学习“Java免费学习笔记(深入)”;
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.get(0) 不会触发 IndexOutOfBoundsException。若源数据可能含空分组,建议改用 list.stream().findFirst().orElse(null);
- 稳定性:groupingBy 默认不保证分组内顺序 —— 但因输入 List 有序且 Collectors.toList() 保持插入顺序,故 list.get(0) 确实返回首次出现的元素;
- 性能考量:该方案需完整遍历并构建中间 Map 和 List,时间复杂度 O(n),空间复杂度 O(n)。对超大数据集,可考虑 TreeSet 自定义 Comparator 或第三方库(如 Eclipse Collections)优化;
-
替代简洁写法(无中间 Map):使用 Collectors.toMap 配合 BinaryOperator 也能实现,但语义稍弱:
List<Person> firstByCity = new ArrayList<>(people.stream() .collect(Collectors.toMap( Person::getCity, Function.identity(), (existing, replacement) -> existing // 保留第一个 )).values());
✅ 总结
按属性获取每组首个对象的核心在于「分组 → 提取首项」两步流水线。推荐优先采用 groupingBy + values().stream().map(...get(0)) 组合,逻辑直观、易于维护;必要时再通过泛型工具方法提升复用性。始终关注空值与顺序保障,即可稳健应对各类业务去重场景。










