【求助】JAVA8 List<Map<>>中过滤出重复元素问题

问题描述
如下所示List数据结构:
List>list=newArrayList<>();
Mapmap1=newHashMap<>();
map1.put("order_no","123");
map1.put("quantity",10);
map1.put("amount",100);
Mapmap2=newHashMap<>();
map2.put("order_no","223");
map2.put("quantity",15);
map2.put("amount",150);
Mapmap3=newHashMap<>();
map3.put("order_no","123");
map3.put("quantity",5);
map3.put("amount",50);
Mapmap4=newHashMap<>();
map4.put("order_no","124");
map4.put("quantity",6);
map4.put("amount",60);
Mapmap5=newHashMap<>();
map5.put("order_no","223");
map5.put("quantity",7);
map5.put("amount",70);
list.add(map1);
list.add(map2);
list.add(map3);
list.add(map4);
list.add(map5);
有个需求是判断上述list中,是否存在有Map.key=order_no,其value重复,并将重复的项取出,如例子所示最后应该会抓到order_no=123,223,这两笔订单,我目前的写法是:
//定义一个过渡用的list2与list一致
List>list2=newArrayList<>();
list2.addAll(list);
List>collect=list.stream().filter(x->{
longcount=list2.stream().filter(x2->x2.get("order_no").equals(x.get("order_no"))).count();
if(count>1){//判断是否重复
returntrue;
}
returnfalse;
}).collect(Collectors.groupingBy(x->x.get("order_no"))).entrySet().stream().map(x->{
Maptmp=newHashMap<>();
tmp.put("key_order",x.getKey());
tmp.put("order_list",x.getValue());
returntmp;//分组展示重复的订单数据
}).collect(Collectors.toList());
目前虽然功能是实现的,但是考虑到订单量有数万笔乃至更多,重新定义了一个一样的过渡用list这样的写法比较粗糙,效能也不高,想请教下大家有没有更简洁高效优雅些的方式可以实现功能呢?
慕婉清6462132
浏览 4253回答 2
2回答

料青山看我应如是

...你用set检查重复不就好了吗一遍循环就好了你这个太吓人Setset=newHashSet();MapvalMap=newHashMap();for(Mapitem:list){Stringid=item.get("order_no").toString();if(set.contains(id)){Listl=valMap.computeIfAbsent(id,k->newArrayList());l.add(item);}set.add(id);}for(Map.Entryentry:valMap.entrySet()){System.out.println(JSON.toJSONString(entry.getValue()));}//print//[{"order_no":"123","amount":50,"quantity":5}]//[{"order_no":"223","amount":70,"quantity":7}]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript