Java8 - Collections.groupingBy()分组

本文演示了如何使用Java中的Collections.groupingBy方法对People对象列表进行单字段(address)和多字段(address与age组合)的分组操作。通过示例代码展示了如何收集并打印分组后的结果,帮助理解groupingBy的用法。
摘要由CSDN通过智能技术生成

1、Collections.groupingBy() 单字段分组

@ToString
@Data
@AllArgsConstructor
public class People {

    private Integer id;
    private String name;
    private String address;
    private Integer age;
}

测试类

public static void main(String[] args) {
        People people1 = new People(1, "only-qi1", "11", 11);
        People people2 = new People(2, "only-qi2", "12", 12);
        People people3 = new People(3, "only-qi3", "14", 13);
        People people4 = new People(1, "only-qi4", "14", 14);
        People people5 = new People(2, "only-qi5", "13", 15);
        People people6 = new People(1, "only-qi6", "11", 11);
        ArrayList<People> arrayList = new ArrayList<>();
        arrayList.add(people1);
        arrayList.add(people2);
        arrayList.add(people3);
        arrayList.add(people4);
        arrayList.add(people5);
        arrayList.add(people6);
        
        Map<String, List<People>> map = arrayList.stream().collect(Collectors.groupingBy(People::getAddress));
        for (String s : map.keySet()) {
            System.out.println("key值是:" + s + "=========" + "value的值是" + map.get(s));
        }
    }

测试结果:
在这里插入图片描述

2、Collections.groupingBy() 多字段分组
 Map<String, List<People>> map1 = arrayList.stream().collect(Collectors.groupingBy(p->p.getAddress()+"#"+p.getAge()));
        for (String s : map1.keySet()) {
            System.out.println("key值是:" + s + "=========" + "value的值是" + map1.get(s));
        }

测试结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值