交并集结果集合设置初始化大小,避免扩容成本

This commit is contained in:
nickChenyx
2020-09-23 11:17:29 +08:00
parent 36f7909702
commit 9e9405c36e

View File

@@ -104,12 +104,13 @@ public class CollUtil {
* @return 并集的集合,返回 {@link ArrayList}
*/
public static <T> Collection<T> union(Collection<T> coll1, Collection<T> coll2) {
final ArrayList<T> list = new ArrayList<>();
if (isEmpty(coll1)) {
list.addAll(coll2);
return new ArrayList<>(coll2);
} else if (isEmpty(coll2)) {
list.addAll(coll1);
} else {
return new ArrayList<>(coll1);
}
final ArrayList<T> list = new ArrayList<>(Math.max(coll1.size(), coll2.size()));
final Map<T, Integer> map1 = countMap(coll1);
final Map<T, Integer> map2 = countMap(coll2);
final Set<T> elts = newHashSet(coll2);
@@ -121,7 +122,6 @@ public class CollUtil {
list.add(t);
}
}
}
return list;
}
@@ -226,8 +226,8 @@ public class CollUtil {
* @return 交集的集合,返回 {@link ArrayList}
*/
public static <T> Collection<T> intersection(Collection<T> coll1, Collection<T> coll2) {
final ArrayList<T> list = new ArrayList<>();
if (isNotEmpty(coll1) && isNotEmpty(coll2)) {
final ArrayList<T> list = new ArrayList<>(Math.min(coll1.size(), coll2.size()));
final Map<T, Integer> map1 = countMap(coll1);
final Map<T, Integer> map2 = countMap(coll2);
final Set<T> elts = newHashSet(coll2);
@@ -238,10 +238,12 @@ public class CollUtil {
list.add(t);
}
}
}
return list;
}
return new ArrayList<>();
}
/**
* 多个集合的交集<br>
* 针对一个集合中存在多个相同元素的情况,计算两个集合中此元素的个数,保留最少的个数<br>