org.apache.commons.collections4.CollectionUtils
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
2.并集CollectionUtils.union(listA,listB)
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个数组取并集 [A, B, C, D, E, F, G, H, K]
System.out.println(ArrayUtils.toString(CollectionUtils.union(listA, listB)));
3.交集CollectionUtils.intersection(listA, listB)
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个数组取交集 [B, D, F]
System.out.println(ArrayUtils.toString(CollectionUtils.intersection(listA, listB)));
// 补集、差集 略
4.集合是否为空或不为空
// 集合是否为空
CollectionUtils.isEmpty(new ArrayList<>()); // true
CollectionUtils.isEmpty(null); // true
List<Person> boy = new ArrayList<>();
boy.add(new Girl());
CollectionUtils.isEmpty(boy); // false
// 集合是否不为空
CollectionUtils.isNotEmpty(new ArrayList<>()); // false
CollectionUtils.isNotEmpty(null); // false
List<Person> boy = new ArrayList<>();
boy.add(new Girl());
CollectionUtils.isNotEmpty(boy); // true
5.集合是否相等
class Person{
// ...
}
class Girl extends Person{
// ...
}
List<Integer> first = new ArrayList<>();
List<Integer> second = new ArrayList<>();
first.add(1);
first.add(2);
second.add(2);
second.add(1);
Girl goldGirl = new Girl();
List<Person> boy1 = new ArrayList<>();
boy1.add(new Girl());
List<Person> boy2 = new ArrayList<>();
boy2.add(new Girl());
List<Person> boy3 = new ArrayList<>();
boy3.add(goldGirl);
List<Person> boy4 = new ArrayList<>();
boy4.add(goldGirl);
// 比较两集合值
System.out.println(CollectionUtils.isEqualCollection(first,second)); //true
System.out.println(CollectionUtils.isEqualCollection(first,boy1)); //false
System.out.println(CollectionUtils.isEqualCollection(boy1,boy2)); //false
System.out.println(CollectionUtils.isEqualCollection(boy3,boy4)); //true
标签:常用,java,List,ArrayList,CollectionUtils,add,new,false
From: https://www.cnblogs.com/AlwaysStudying/p/17236497.html