「这是我参与2022首次更文挑战的第16天,活动详情查看:2022首次更文挑战」
前言
今天继续hutool工具类的认识,废话不多说下面直接进入主题。
一.集合相关工具类,CollUtil,老规矩看类图知方法,接下来挑几个常用的进行讲解.
1.emptyIfNull类似collections.empty功能,这里就不多赘述
2.union,两个或三个集合的并集这个方法在一定程度上非常好用,看一下下来的例子就知道了,类似list的并集操作,但是list操作是listA.removeAll(listB),listA.addAll(listB)
ArrayList<String> list1 = CollUtil.newArrayList("1", "2", "3", "4");
ArrayList<String> list2 = CollUtil.newArrayList("2","5", "6");
Collection<String> union = CollUtil.union(list1, list2);
输出结果:[1, 2, 3, 4, 5, 6] 扩展类unionDistinct是多个集合的非重复并集,实现代码很简单利用了LinkedHashSet元素不重复的特性,当然在实际开发中我们也可以仿照这种模式去编写适用于业务的工具类 3.intersection,两个集合的交集,list的操作是listA.retainAll(listB),下面看看intersection的操作,当然其扩展类也支持多个集合,而intersectionDistinct也是同类似的功能
public static <T> Collection<T> intersection(Collection<T> coll1, Collection<T> coll2) {
if (isNotEmpty(coll1) && isNotEmpty(coll2)) {
final ArrayList<T> list = new ArrayList<>(Math.min(coll1.size(), coll2.size()));
//countMap的作用是根据集合返回一个元素计数的Map
final Map<T, Integer> map1 = countMap(coll1);
final Map<T, Integer> map2 = countMap(coll2);
final Set<T> elts = newHashSet(coll2);
int m;
//循环上面的set找两个Map中最小的数字然后放入list中,最后返回list
for (T t : elts) {
m = Math.min(Convert.toInt(map1.get(t), 0), Convert.toInt(map2.get(t), 0));
for (int i = 0; i < m; i++) {
list.add(t);
}
}
return list;
}
return new ArrayList<>();
}
4.disjunction,两个集合的差集,list里相对简单,使用removeAll就能实现,我们再来看看disjunction的操作
public static <T> Collection<T> disjunction(Collection<T> coll1, Collection<T> coll2) {
if (isEmpty(coll1)) {
return coll2;
}
if (isEmpty(coll2)) {
return coll1;
}
final List<T> result = new ArrayList<>();
//同样根据集合的size创建size个元素的Map
final Map<T, Integer> map1 = countMap(coll1);
final Map<T, Integer> map2 = countMap(coll2);
final Set<T> elts = newHashSet(coll2);
elts.addAll(coll1);
int m;
//循环上面的list 相互比较,把相差的个数记录,返回两个map中除去元素值相同的元素保留不一样的元素
for (T t : elts) {
m = Math.abs(Convert.toInt(map1.get(t), 0) - Convert.toInt(map2.get(t), 0));
for (int i = 0; i < m; i++) {
result.add(t);
}
}
return result;
}
5.subtract,计算集合的单差集,即返回集合1中有集合2无的元素,代码如下:
public static <T> Collection<T> subtract(Collection<T> coll1, Collection<T> coll2) {
//先克隆集合1
Collection<T> result = ObjectUtil.clone(coll1);
//如果集合1无元素则创建一个空的集合1
if (null == result) {
result = CollUtil.create(coll1.getClass());
result.addAll(coll1);
}
//从集合1中剔除掉集合2的元素
result.removeAll(coll2);
return result;
}
小结
hutool的工具类有很多类似之处,看着代码很简单但是很实用,我们在平常的开发中也可以借鉴,写属于自己的工具类,加油。