目录
1、Pom包
从maven找到最新jar包如下:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.3</version>
</dependency>
2、常用方法
2.1、集合判断
判断集合是否为空:
CollectionUtils.isEmpty(null): true
CollectionUtils.isEmpty(new ArrayList()): true
CollectionUtils.isEmpty({a,b}): false
判断集合是否不为空:
CollectionUtils.isNotEmpty(null): false
CollectionUtils.isNotEmpty(new ArrayList()): false
CollectionUtils.isNotEmpty({a,b}): true
源码分析
public class CollectionUtils {
public static boolean isEmpty(Collection<?> coll) {
return coll == null || coll.isEmpty();
}
public boolean isEmpty() {
return size == 0;
}
}
2.2、并集
public class TestCollectionUtils {
public static void main(String[] args) {
String[] arrayA = new String[] { "A", "B", "C", "D", "E", "F" };
String[] arrayB = new String[] { "B", "D", "F", "G", "H", "K" };
List<String> listA = Arrays.asList(arrayA);
List<String> listB = Arrays.asList(arrayB);
//2个数组取并集
System.out.println(ArrayUtils.toString(CollectionUtils.union(listA, listB)));
//[A, B, C, D, E, F, G, H, K]
}
}
2.3、交集
public class TestCollectionUtils {
public static void main(String[] args) {
String[] arrayA = new String[] { "A", "B", "C", "D", "E", "F" };
String[] arrayB = new String[] { "B", "D", "F", "G", "H", "K" };
List<String> listA = Arrays.asList(arrayA);
List<String> listB = Arrays.asList(arrayB);
//2个数组取交集
System.out.println(ArrayUtils.toString(CollectionUtils.intersection(listA, listB)));
//[B, D, F]
}
}
2.4、交集的补集(析取)
public class TestCollectionUtils {
public static void main(String[] args) {
String[] arrayA = new String[] { "A", "B", "C", "D", "E", "F" };
String[] arrayB = new String[] { "B", "D", "F", "G", "H", "K" };
List<String> listA = Arrays.asList(arrayA);
List<String> listB = Arrays.asList(arrayB);
//2个数组取交集 的补集
System.out.println(ArrayUtils.toString(CollectionUtils.disjunction(listA, listB)));
//[A, C, E, G, H, K]
}
}
2.5、差集
public class TestCollectionUtils {
public static void main(String[] args) {
String[] arrayA = new String[] { "A", "B", "C", "D", "E", "F" };
String[] arrayB = new String[] { "B", "D", "F", "G", "H", "K" };
List<String> listA = Arrays.asList(arrayA);
List<String> listB = Arrays.asList(arrayB);
//arrayA扣除arrayB
System.out.println(ArrayUtils.toString(CollectionUtils.subtract(listA, listB)));
//[A, C, E]
}
}
2.6、不可修改的集合【已经过期】
public class TestCollectionUtils {
public static void main(String[] args) {
Collection<String> c = new ArrayList<>();
//deprecated
Collection<String> s = CollectionUtils.unmodifiableCollection(c);
c.add("a");
c.add("b");
c.add("c");
//Exception in thread "main" java.lang.UnsupportedOperationException
//s.add("have a error");
System.out.println(s);
}
}