CollectionUtils方法
Posted jet-angle
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CollectionUtils方法相关的知识,希望对你有一定的参考价值。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.CollectionUtils;
public class LearnCollection {
public static void main(String[] args) {
List<Integer> num1=new ArrayList<Integer>();
num1.addAll(Arrays.asList(1,2,3,3));
System.out.println("num1:"+num1);
List<Integer> num2=new ArrayList<Integer>();
num2.addAll(Arrays.asList(3,3,3,4,5));
System.out.println("num2:"+num2);
/**
* union 并集
* The cardinality of each element in the returned Collection will be
* equal to the maximum of the cardinality of that element in the two
* given Collections.
*/
Collection<Integer> res1=CollectionUtils.union(num1, num2);
System.out.println("并集:"+res1);
/**
* intersection 交集
* The cardinality of each element in the returned Collection will be
* equal to the minimum of the cardinality of that element in the two given
* Collections.
*
*/
Collection<Integer> res2=CollectionUtils.intersection(num1, num2);
System.out.println("交集:"+res2);
/**
* 是否存在交集 containsAny
*/
System.out.println("是否存在交集:"+CollectionUtils.containsAny(num1, num2));
/**
* 交集的补集 disjunction
* equivalent to subtract(union(a,b),intersection(a,b))
*/
Collection<Integer> res3=CollectionUtils.disjunction(num1, num2);
System.out.println("交集的补集:"+res3);
/**
* 差集 subtract
* The cardinality of each element e in the returned Collection
* will be the cardinality of e in a minus the cardinality of e in b, or zero
*/
Collection<Integer> res4=CollectionUtils.subtract(num2, num1);
System.out.println("差集:"+res4);
/**
* 判断是否是子集 集合A中每个元素的个数都大于另一个B中对应元素的个数,B是A的子集
*/
System.out.println("num1是不是num2的子集:"+CollectionUtils.isSubCollection(num1, num2));
/**
* 还有很多其他函数,不一一列举
*/
/**
* 返回一个map,统计每个元素出现的次数
* Returns a Map mapping each unique element in the given Collection
* to an Integer representing the number of occurrences of that element
* in the Collection.
*/
Map<Integer, Integer> map=CollectionUtils.getCardinalityMap(num2);
System.out.println("元素--个数:"+map);
}
}
以上是关于CollectionUtils方法的主要内容,如果未能解决你的问题,请参考以下文章