java归类统计List<Map>中某个字段其元素值个数

/**
*
*
*list:[{id:"1",name:"公司1"},{id:"2",name:"公司2"},{id:"3",name:"公司1"}}
*
*/

Map<String, Long> org_map = list.stream().collect(
                Collectors.groupingBy(org-> org.get("name"), Collectors.counting()));



org_map .forEach((k, v) -> {
            System.out.println(k + " -> " + v);
        });

输出:

公司1->2
公司2->1

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Array.prototype.reduce() 方法来实现这个功能。具体步骤如下: 1. 遍历数组,对于每个元素,获取需要归类属性。 2. 在 reduce() 方法创建一个对象,用于保存归类后的结果。 3. 对于每个元素,检查对象是否已经存在该属性对应的数组,如果不存在,则创建一个新数组,并将该元素添加到数组;如果已经存在,则将该元素添加到对应的数组。 4. 最后,将对象转换为数组,即可得到归类后的结果。 下面是一个示例代码: ```javascript const arr = [ { name: 'apple', type: 'fruit' }, { name: 'banana', type: 'fruit' }, { name: 'carrot', type: 'vegetable' }, { name: 'orange', type: 'fruit' }, { name: 'broccoli', type: 'vegetable' }, { name: 'pear', type: 'fruit' }, { name: 'tomato', type: 'vegetable' }, { name: 'pepper', type: 'vegetable' }, { name: 'grape', type: 'fruit' }, { name: 'potato', type: 'vegetable' }, ]; const result = arr.reduce((obj, item) => { if (obj[item.type]) { obj[item.type].push(item); } else { obj[item.type] = [item]; } return obj; }, {}); console.log(result); ``` 输出结果为: ```javascript { fruit: [ { name: 'apple', type: 'fruit' }, { name: 'banana', type: 'fruit' }, { name: 'orange', type: 'fruit' }, { name: 'pear', type: 'fruit' }, { name: 'grape', type: 'fruit' } ], vegetable: [ { name: 'carrot', type: 'vegetable' }, { name: 'broccoli', type: 'vegetable' }, { name: 'tomato', type: 'vegetable' }, { name: 'pepper', type: 'vegetable' }, { name: 'potato', type: 'vegetable' } ] } ``` 在这个示例,我们将 `arr` 数组元素按照 `type` 属性进行归类,得到一个包含 `fruit` 和 `vegetable` 两个属性的对象。每个属性对应一个数组,包含相同 `type` 属性元素

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值