码迷,mamicode.com
首页 > 其他好文 > 详细

CollectionUtils常用方法

时间:2020-05-27 15:14:53      阅读:50      评论:0      收藏:0      [点我收藏+]

标签:oar   apach   containe   nsa   version   com   png   script   alt   

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常用方法

标签:oar   apach   containe   nsa   version   com   png   script   alt   

原文地址:https://www.cnblogs.com/mjtabu/p/12973000.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!