使用Java8的流可以很方便的对List进行多种操作,如分组、去重、过滤等,本文分享如何根据List中Map的多个条件进行去重。
首先,创建一个测试用的List:
Map<String, String> map1 = new HashMap<>();
Map<String, String> map2 = new HashMap<>();
Map<String, String> map3 = new HashMap<>();
map1.put("id", "a1");
map1.put("name", "shigure");
map1.put("age", "22");
map2.put("id", "a1");
map2.put("name", "shigure");
map2.put("age", "32");
map3.put("id", "a2");
map3.put("name", "test");
map3.put("age", "32");
List<Map<String, String>> list = Arrays.asList(map1, map2, map3);
然后根据Map中的id和name字段进行去重:
//结果放在list中
List<Map<String, String>> distinctList = list.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(() ->
new TreeSet<>(Comparator.comparing(value -> value.get("id") + ";" + value.get("name")))),
ArrayList::new));
//结果放在set中
Set<Map<String, String>> set = list.stream()
.collect(Collectors.toCollection(() ->
new TreeSet<>(Comparator.comparing(value -> value.get("id") + ";" + value.get("name")))));
去重前和去重后的结果对比:
对于未参与去重条件的字段,将以第一个出现的为准,比如这个例子,"id" -> "a1", "name" -> "shigure"最终去重后的结果,"age"字段为首次加入list中的"22"
去重前:[{name=shigure, id=a1, age=22}, {name=shigure, id=a1, age=32}, {name=test, id=a2, age=32}]
去重后:[{name=shigure, id=a1, age=22}, {name=test, id=a2, age=32}]