Java stream多字段分组(groupingBy)

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()));

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值