HashSet是一个没有重复元素的集合,可以利用这个特性,把List中的元素逐一添加到HashSet中,最终得到的就是没有重复元素的结果:
packagecom.sample.algo.list;importjava.util.*;importjava.util.function.Function;importjava.util.stream.Collectors;//使用mergeFunction来进行合并publicclassMergeWithMap{publicstaticvoidmain(String[]args){List<Integer>list1=newArrayList<>(Arrays.asList(1,2,3,4,5));List<Integer>list2=newArrayList<>(Arrays.asList(4,5,6));//合并成一个listList<Integer>listAll=newArrayList<>(list1);listAll.addAll(list2);//这样写会抛出Duplicatekey异常//Map<Integer,Integer>map=listAll.stream().//collect(Collectors.toMap(Integer::intValue,(p)->p));//处理相同key的情况,也就是取其中一个Map<Integer,Integer>map=listAll.stream().collect(Collectors.toMap(Integer::intValue,Function.identity(),(first,second)->second));List<Integer>result=newArrayList<>(map.keySet());System.out.println("去重后的List:"+result);}}
推荐阅读:
本篇文章来源于微信公众号: 互联网全栈架构
微信扫描下方的二维码阅读本文

Comments NOTHING