前言:
removeAll方法是取差集的,數據量很大的時候效率很低。
本文的最終方案是方法3
正文:
原集合:List<T> source
目標集合:List<T> destination
要求:取原集合中,不與目標集合重復的元素
1,資料表明,給List中add()數據的速度要比從List中remove()數據的快。效果不明顯
public List<T> removeAll_01(List<T> source, List<T> destination) { List<T> result = new LinkedList<T>(); for(T t : source) { if (!destination.contains(t)) { result.add(t); } } return result; }
2,運用Set可以去重這一特性。效率有明顯提升
public List<T> removeAll_02(List<T> source, List<T> destination) { List<T> result = new LinkedList<T>(); Map<T, Integer> sourceMap = new HashMap<T, Integer>(); for (T t : source) { if (sourceMap.containsKey(t)) { //原集合中的重復值 sourceMap.put(t, sourceMap.get(t) + 1); } else { sourceMap.put(t, 1); } } Set<T> all = new HashSet<T>(destination); for (Map.Entry<T, Integer> entry : sourceMap.entrySet()) { T key = entry.getKey(); Integer value = entry.getValue(); if (all.add(key)) { for (int i = 0; i < value; i++) { result.add(key); } } } return result; }
3,用Set.contains()再優化
public List<T> removeAll_03(List<T> source, List<T> destination) { List<T> result = new LinkedList<T>(); Set<T> destinationSet = new HashSet<T>(destination); for(T t : source) { if (!destinationSet.contains(t)) { result.add(t); } } return result; }
參考博客:
List 的 removeAll 方法的效率 - kangxingang的專欄 - CSDN博客
https://blog.csdn.net/kangxingang/article/details/9033491
