childList = childList.stream().collect( Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.get("id").toString()))), ArrayList::new))
使用到了collectingAndThen完成根据属性进行去重的操作,对于该去重操作的关键使用到了collectingAndThen、toCollection、TreeSet,有点难以理解。
//构造一个基于id比较器的treeSet
TreeSet<HashMap<String,Object>> treeSet = new TreeSet<>(Comparator.comparing(o->o.getString("id")));
//将元素塞进treeSet
for (HashMap map : childList){
treeSet.add(map);
}
//转换成List
List<HashMap<String,Object>> result2 = new ArrayList<>(treeSet);
理解根据对象的属性进行去重的核心是,将集合放到TreeSet中,然后再将TreeSet转为List, 其中TreeSet要传入一个根据哪个属性进行比较的比较器,然后使用public ArrayList(Collection<? extends E> c)
将TreeSet放入构造器中生成List。
collectingAndThen:进行结果的收集 ,再进行下一步的处理。
public static<T,A,R,RR> Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream,
Function<R,RR> finisher) {
参数1:stream 流 Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.get("id").toString())))
参数2;ArrayList的有参构造方法: ArrayList::new
最后收集流到List 集合当中:childList.stream().collect