HashSet对List去重
我们都知道List集合是有序可重复的,Set是无序不可重复的,如果要对一个List集合的元素去重,正好可以利用Set的优点;
//strs为存在重复元素的List
List<String> strs = Lists.newArrayList("a","b","a","c");
List<String> distinctStrs = new ArrayList<>(new HashSet<>(strs));
知其然,也要知其所以然,HashSet为什么可以实现去重?
事实上,HashSet是由HashMap来实现的,只要看一下HashSet的构造方法和add方法就能理解了。
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
由此可以看出HashSet的去重就是根据HashMap实现的,而HashMap的实现又完全依赖于hashcode和equals方法。
Stream对list去重
想到list的操作,我们必须想到lambda表达式,
//返回一个由不同元素的流distinct()
List<String> distinctStrs strs.stream().distinct().collect(Collectors.toList());
参考:https://www.cnblogs.com/woshimrf/p/java-list-distinct.html
作者 Ryan Miao对上述2种方法写得真的详细,推荐 值得一看;我这里只是简单的做个笔记~
下面简单附上集合的属性图: