private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
public static void main(String[] args) {
List<Map<String, Object>> wordItems = new ArrayList<>();
Map<String, Object> map1 = new HashMap();
map1.put("a",2);
map1.put("b",1);
map1.put("c",2);
wordItems.add(map1);
Map<String, Object> map2 = new HashMap();
map2.put("a",21);
map2.put("b",2);
wordItems.add(map2);
Map<String, Object> map3= new HashMap();
map3.put("a",2);
map3.put("b",3);
map3.put("c",3);
wordItems.add(map3);
Map<String, Object> map4= new HashMap();
map4.put("b",4);
map4.put("c",3);
wordItems.add(map4);
Map<String, Object> map5= new HashMap();
map4.put("b",5);
map4.put("a",5);
map4.put("c",5);
wordItems.add(map5);
wordItems = wordItems.stream().filter(keyMap -> keyMap.containsKey("a")).filter(distinctByKey(map -> map.get("a"))).collect(Collectors.toList());
System.out.println(JSONUtil.toJsonStr(wordItems));
}
?
|