CollectionUtils常用方法
作者:互联网
CollectionUtils常用方法
- 是否存在交集:boolean isContained = CollectionUtils.containsAny(aList, bList);
- 并集:Collection<String> unionList = CollectionUtils.union(aList, bList);
- 交集:Collection<String> intersectionList = CollectionUtils.intersection(aList, bList);
- 交集的补集:Collection<String> disjunctionList = CollectionUtils.disjunction(aList, bList);
- 集合相减:Collection<String> subtractList = CollectionUtils.subtract(aList, bList);
依赖jar包:commons-collections4-4.4.jar
代码测试
import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang.ArrayUtils; /** * @author 踏步 * @version 创建时间:2020年5月27日下午2:00:00 * @Description:TODO 测试类 */ 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> aList = Arrays.asList(arrayA); List<String> bList = Arrays.asList(arrayB); // 是否存在交集 boolean isContained = CollectionUtils.containsAny(aList, bList); // 并集 Collection<String> unionList = CollectionUtils.union(aList, bList); // 交集 Collection<String> intersectionList = CollectionUtils.intersection(aList, bList); // 交集的补集 Collection<String> disjunctionList = CollectionUtils.disjunction(aList, bList); // 集合相减 Collection<String> subtractList = CollectionUtils.subtract(aList, bList); // 排序 Collections.sort((List<String>) unionList); Collections.sort((List<String>) intersectionList); Collections.sort((List<String>) disjunctionList); Collections.sort((List<String>) subtractList); // 测试结果 System.out.println("集合--A: " + ArrayUtils.toString(aList.toArray())); System.out.println("集合--B: " + ArrayUtils.toString(bList.toArray())); System.out.println("是否存在交集--A has one of B? : " + isContained); System.out.println("并集--Union(A, B): " + ArrayUtils.toString(unionList.toArray())); System.out.println("交集--Intersection(A, B): " + ArrayUtils.toString(intersectionList.toArray())); System.out.println("交集的补集--Disjunction(A, B): " + ArrayUtils.toString(disjunctionList.toArray())); System.out.println("集合相减--Subtract(A, B): " + ArrayUtils.toString(subtractList.toArray())); } }
测试结果
标签:常用,交集,aList,CollectionUtils,Collection,bList,ArrayUtils,方法 来源: https://blog.51cto.com/u_15222067/2834307