如何通过Collector直接将List<Persons>按姓氏分组为List<List>
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 yourPersonsobjects into aMap<String, List<Persons>>where keys are family names.- The
collectingAndThenwrapper takes that map and immediately converts its collection of values (the grouped lists) into anArrayList, 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

