使用Java8的流可以很方便的对List进行多种操作,如分组、去重、过滤等,本文分享如何根据List中Map的多个条件进行去重。
首先,创建一个测试用的List:
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map = new HashMap<>();
map.put("id", "a1");
map.put("name", "shigure");
map.put("age", "22");
list.add(new HashMap<>(map));
map.put("id", "a1");
map.put("name", "shigure");
map.put("age", "22");
list.add(new HashMap<>(map));
map.put("id", "a1");
map.put("name", "shigure2");
map.put("age", "22");
list.add(new HashMap<>(map));
map.put("id", "a2");
map.put("name", "test");
map.put("age", "32");
list.add(new HashMap<>(map));
然后根据Map中的id和name字段进行去重:
list = list.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() ->
new TreeSet<>(Comparator.comparing((o)-> o.get("id") + ";" + o.get("name")))), ArrayList::new));
去重前和去重后的结果对比:
去重前:[{name=shigure, id=a1, age=22}, {name=shigure, id=a1, age=22}, {name=shigure2, id=a1, age=22}, {name=test, id=a2, age=32}]
去重后:[{name=shigure, id=a1, age=22}, {name=shigure2, id=a1, age=22}, {name=test, id=a2, age=32}]
|