CollectionUtils常用方法
Posted mjtabu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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())); } }
测试结果
以上是关于CollectionUtils常用方法的主要内容,如果未能解决你的问题,请参考以下文章
elasticsearch代码片段,及工具类SearchEsUtil.java