java8分组_使用java8特性实现分组

List items = Arrays.asList(

new Item("apple", 10, new BigDecimal(23.5)),

new Item("apple", 20, new BigDecimal(32.5)),

new Item("orange", 30, new BigDecimal(20)),

new Item("orange", 20, new BigDecimal(32.5)),

new Item("orange", 10, new BigDecimal(63.5)),

new Item("orange", 50, new BigDecimal(41.5)),

new Item("peach", 20, new BigDecimal(26.5)),

new Item("peach", 30, new BigDecimal(32.5)),

new Item("peach", 40, new BigDecimal(24.5)),

new Item("peach", 10, new BigDecimal(12.5))

);

//不使用java8特性的写法

Map> resultMap = new HashMap<>(1024);

for (Item item : items) {

List tempList = resultMap.get(item.getName());

//如果取不到数据,那么直接new一个空的ArrayList*

if (tempList == null) {

tempList = new ArrayList<>();

tempList.add(item);

resultMap.put(item.getName(), tempList);

} else {

//某个alarmSourceInfoEntity之前已经存放过了,则直接追加数据到原来的List里*

tempList.add(item);

}

}

// 使用java8特性

Map> groupByPriceMap = items.stream()

.collect(Collectors.groupingBy(Item::getName));

//另一种写法

/*Map> alarmSourceMap1 = items

.stream().collect(Collectors.toMap(Item::getName,

p ->{

List list = new ArrayList<>();

list.add(p);

return list;

},(List value1, List value2) -> {

value1.addAll(value2);

return value1;

}));*/

for (Map.Entry entry:resultMap.entrySet()) {

System.out.println(entry.getKey()+":"+entry.getValue());

}

System.out.println("********************************************");

for (Map.Entry entry:groupByPriceMap.entrySet()) {

System.out.println(entry.getKey()+":"+entry.getValue());

}执行结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值