Java List 按名称分组:使用 Stream API 和 Collectors.groupingBy
可以使用 Java 8 中的 Stream API 和 Collectors.groupingBy 方法来按照名称对 List 进行分组。
假设我们有一个 Person 类,它有两个属性:name 和 age。
首先,我们需要将 List 转换为 Stream:
List<Person> personList = ...; // 假设这是我们要分组的 List
Map<String, List<Person>> personGroups = personList.stream()
.collect(Collectors.groupingBy(Person::getName));
在上述代码中,我们使用 Person::getName 作为分组依据,将 List<Person> 分组为 Map<String, List<Person>>,其中 Map 的键是名称,值是该名称对应的所有 Person 对象的 List。
如果我们想要进一步对分组后的结果进行操作,例如,统计每个名称分组中的 Person 对象数量,可以使用 Collectors.counting 方法:
Map<String, Long> personCountMap = personList.stream()
.collect(Collectors.groupingBy(Person::getName, Collectors.counting()));
在上述代码中,我们使用 Person::getName 作为分组依据,将 List<Person> 分组为 Map<String, Long>,其中 Map 的键是名称,值是该名称对应的 Person 对象数量。
原文地址: https://www.cveoy.top/t/topic/ol89 著作权归作者所有。请勿转载和采集!