public class TestGroupingBy {
public static void main(String[] args) {
List<Person> personList = Arrays.asList(
new Person().setId(1).setAge(18).setType("student").setName("user - 1").setGender("male"),
new Person().setId(2).setAge(20).setType("student").setName("user - 2").setGender("male"),
new Person().setId(3).setAge(18).setType("student").setName("user - 3").setGender("male"),
new Person().setId(4).setAge(18).setType("student").setName("user - 4").setGender("male"),
new Person().setId(5).setAge(35).setType("teacher").setName("user - 5").setGender("male"),
new Person().setId(6).setAge(35).setType("teacher").setName("user - 6").setGender("male"),
new Person().setId(7).setAge(20).setType("student").setName("user - 7").setGender("male"),
new Person().setId(8).setAge(20).setType("student").setName("user - 8").setGender("female"),
new Person().setId(9).setAge(20).setType("student").setName("user - 9").setGender("female"),
new Person().setId(10).setAge(20).setType("student").setName("user - 10").setGender("female")
);
// 定义一个函数Function,该函数将元素对象映射到一个键的集合里
Function<Person, List<Object>> compositeKey = person ->
Arrays.asList(person.getGender(), person.getAge(), person.getType());
// 分组
Map<List<Object>, List<Person>> groupingMap =
personList.stream().collect(Collectors.groupingBy(compositeKey, Collectors.toList()));
// 简化
Map<List<Object>, List<Person>> groupingMap =
personList.stream().collect(Collectors.groupingBy(person ->
Arrays.asList(person.getGender(), person.getAge(), person.getType()), Collectors.toList()));
}
}
Java stream多字段分组(groupingBy)
最新推荐文章于 2025-04-16 09:31:44 发布