欢迎关注作者博客
简书传送门
前言
论阅读源码的重要性,后期会对各大开源框架相关源码做详细阅读,并熟悉使用,本次主要对Apache Commons Collections中CollectionUtils类进行示例分析,如有错误,请多指教。
通过apache-commons包中的org.apache.commons.collections.CollectionUtils集合操作工具类 对集合间进行合并union、交叉intersection、分离disjunction、减去subtract、任意包含containsAny、判断是否为子集isSubCollection、颠倒序列reverseArray及判断是否填满isFull等操作。
代码示例
package com.zzx.apache.commons.chapter1;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.junit.jupiter.api.Test;
import java.util.*;
/**
* <p>
* 通过apache-commons包中的org.apache.commons.collections.CollectionUtils集合操作工具类 对集合间进行合并union、交叉intersection、分离disjunction、减去subtract、任意包含containsAny、
* 判断是否为子集isSubCollection、颠倒序列reverseArray及判断是否填满isFull等操作。
* </p>
**/
public class CollectionsUtilsDemo {
/** Arrays.asList()返回的是Arrays内部类ArraysList,不可对其进行add、remove等操作,返回报UnsupportedOperationException */
/** java.util.ArrayList和Arrays内部类ArraysList都继承AbstractList,remove、add等方法AbstractList中是默认throw UnsupportedOperationException而且不作任何操作。*/
/** java.util.ArrayList重新了这些方法而Arrays的内部类ArrayList没有重新,所以会抛出异常。*/
// @Deprecated
// private static List<String> list1 = Arrays.asList(new String[] {"1", "2", "3", "1"});
// @Deprecated
// private static List<String> list2 = Arrays.asList(new String[] {"2", "3", "4"});
// @Deprecated
// private static List<String> list3 = Arrays.asList(new String[] {"1", "2"});
/** 解决 */
private static List<String> list1 = new ArrayList<>(Arrays.asList(new String[] {
"1", "2", "3", "1", "5"}));
private static List<String> list2 = new ArrayList<>(Arrays.asList(new String[] {
"2", "3", "1"}));
private static List<String> list3 = new ArrayList<>(Arrays.asList(new String[] {
"1", "2"}));
@Data
class Employee {
private String name;
private String email;
private int age;
private double salary;
/** 是否在职 */
private boolean activeEmployee;
public Employee(String name, String email, int age, double salary, boolean activeEmployee) {
this.name = name;
this.email = email;
this.age = age;
this.salary = salary;
this.activeEmployee = activeEmployee;
}
}
/**
* 判断两个集合是否和相同元素
*/
public void containsAnyT1() {
// 判断两个集合是否和相同元素
boolean b = CollectionUtils.containsAny(list1, list2);
System.out.println(b);
}
/**
* 得到两个集合中相同的元素
*/
@Test
public