利用JAVA8自建个工具类求集合交集,并集,差集

public class CollectionUtil {

    /**
     * 判断为空
     * @param collection
     * @return
     */
    public static boolean isEmpty(Collection collection) {

        return (collection == null || collection.isEmpty());

    }

    /**
     * 判断非空
     * @param collection
     * @return
     */
    public static boolean isNotEmpty(Collection collection) {

        return !isEmpty(collection);

    }

    /**
     * 求交集
     * @param masterList 主数据列表
     * @param slaveList 从数据列表
     * @param 
     * @return
     */

    public static  List getIntersection(List masterList, List slaveList) {

        return masterList.stream().filter(slaveList::contains).collect(Collectors.toList());

    }


    /**
     * 求并集
     * @param masterList 主数据列表
     * @param slaveList 从数据列表
     * @param 
     * @return
     */

    public static  List getUnionSet(List masterList, List slaveList) {

        List list = new ArrayList<>();

        list.addAll(masterList);

        list.addAll(slaveList);

        return list.stream().distinct().collect(Collectors.toList());

    }

    /**
     * 求差集
     * @param masterList 主数据列表
     * @param slaveList 从数据列表
     * @param 
     * @return
     */

    public static  List getDifferenceSet(List masterList, List slaveList) {

        return masterList.stream().filter(t -> !slaveList.contains(t)).collect(Collectors.toList());

    }

    //测试函数
    public static void main(String[] args) {
        List list1 = Arrays.asList(1, 2, 3);
        List list2 = Arrays.asList(3, 4, 5);
        System.out.println("=========求交集=========");
        List intersection = CollectionUtil.getIntersection(list1,list2);
        intersection.forEach(System.out::println);

        System.out.println("=========求并集=========");
        List unionSet = CollectionUtil.getUnionSet(list1,list2);
        unionSet.forEach(System.out::println);

        System.out.println("=========求交集=========");
        List differenceSet = CollectionUtil.getDifferenceSet(list1,list2);
        differenceSet.forEach(System.out::println);
    }
}

控制台打印结果

=========求交集=========
3
=========求并集=========
Disconnected from the target VM, address: '127.0.0.1:61891', transport: 'socket'
1
2
3
4
5
=========求交集=========
1
2

也可以用阿帕奇commons.collections包下的CollectionUtils的工具类

package org.apache.commons.collections

你可能感兴趣的:(Java,加载)