Java中List根据map的某个key去重的代码

今天小编就为大家分享一篇关于Java中List根据map的某个key去重的代码,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

话不多说,看代码和效果

 /** * 根据map中的某个key 去除List中重复的map * @author shijing * @param list * @param mapKey * @return */ public static List> removeRepeatMapByKey(List> list, String mapKey){ if (CollectionUtils.isNullOrEmpty(list)) return null; //把list中的数据转换成msp,去掉同一id值多余数据,保留查找到第一个id值对应的数据 List> listMap = new ArrayList<>(); Map msp = new HashMap<>(); for(int i = list.size()-1 ; i>=0; i--){ Map map = list.get(i); String id = (String)map.get(mapKey); map.remove(mapKey); msp.put(id, map); } //把msp再转换成list,就会得到根据某一字段去掉重复的数据的List Set mspKey = msp.keySet(); for(String key: mspKey){ Map newMap = msp.get(key); newMap.put(mapKey, key); listMap.add(newMap); } return listMap; }

测试:

 public static void main(String[] args) { Map msp = new HashMap(); List> list = new ArrayList>(); List> listMap = new ArrayList>(); Map map1 = new HashMap(); map1.put("id", "1123"); map1.put("name", "张三"); Map map2 = new HashMap(); map2.put("id", "2"); map2.put("name", "李四"); Map map3 = new HashMap(); map3.put("id", "1123"); map3.put("name", "王五"); Map map4 = new HashMap(); map4.put("id", "3"); map4.put("name", "赵六"); list.add(map1); list.add(map2); list.add(map3); list.add(map4); System.out.println("初始数据:" + list.toString()); System.out.println("去重之后:" + removeRepeatMapByKey(list,"id")); }

结果:

初始数据:[{name=张三, id=1123}, {name=李四, id=2}, {name=王五, id=1123}, {name=赵六, id=3}]
去重之后:[{name=李四, id=2}, {name=赵六, id=3}, {name=张三, id=1123}]

总结

以上就是Java中List根据map的某个key去重的代码的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Java