Merge pull request #1110 from nickChenyx/v5-dev

交并集结果集合设置初始化大小,避免扩容成本
This commit is contained in:
Golden Looly
2020-09-23 14:38:05 +08:00
committed by GitHub

View File

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