You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Collector直接将List<Persons>按姓氏分组为List<List>

One-step Collector to Group List<Persons> into List<List<Persons>> by Family Name

Absolutely, you can skip the intermediate Map step and get your desired List<List<Persons>> directly in a single collector chain. The key here is using Collectors.collectingAndThen() to wrap the grouping logic and immediately convert the resulting map's values into a list.

Basic Implementation

Here's the straightforward one-liner:

List<List<Persons>> groupedPersons = personsList.stream()
    .collect(Collectors.collectingAndThen(
        Collectors.groupingBy(Persons::getFamilyName),
        map -> new ArrayList<>(map.values())
    ));

How It Works

  • Collectors.groupingBy(Persons::getFamilyName) first handles grouping your Persons objects into a Map<String, List<Persons>> where keys are family names.
  • The collectingAndThen wrapper takes that map and immediately converts its collection of values (the grouped lists) into an ArrayList, so you don’t need to handle the map explicitly outside the collector.

Preserving Group Order (Optional)

If you want the resulting list of groups to maintain the order in which family names first appeared in your original list, use LinkedHashMap as the backing map for groupingBy (the default HashMap doesn’t preserve insertion order):

List<List<Persons>> orderedGroupedPersons = personsList.stream()
    .collect(Collectors.collectingAndThen(
        Collectors.groupingBy(
            Persons::getFamilyName,
            LinkedHashMap::new,
            Collectors.toList()
        ),
        map -> new ArrayList<>(map.values())
    ));

This ensures the first family name encountered in your input list will be the first group in your output list, and so on.

内容的提问来源于stack exchange,提问作者Manuelarte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:35:58