【Java用法】java 8两个List集合取交集、并集、差集、去重并集

public class ListTest {
 
    public static void main(String[] args) {
 
        ArrayList<String> listA = CollectionUtil.toList("a", "b", "c", "d", "e");
        ArrayList<String> listB = CollectionUtil.toList( "b", "c", "d", "e", "f");
        System.out.println("listA = " + listA);
        System.out.println("listB = " + listB);
        
        // listA和listB的差集(listA - listB)
        List<String> collect = listA.stream().filter(item -> !listB.contains(item)).collect(Collectors.toList());
        System.out.println("listA - listB的差集 = " + collect);
 
        // listA和listB的差集(listB - listA)
        List<String> collect1 = listB.stream().filter(item -> !listA.contains(item)).collect(Collectors.toList());
        System.out.println("listB - listA的差集 = " + collect1);
 
        // listA和listB交集
        List<String> intersection = listA.stream().filter(listB::contains).collect(Collectors.toList());
        System.out.println("listA和listB交集 = " + intersection);
 
        // listA和listB并集(不去重)
        listA.addAll(listB);
        System.out.println("listA和listB并集 = " + listA);
 
        // listA和listB并集(去重)
        List<String> distinctList = listA.stream().distinct().collect(Collectors.toList());
        System.out.println("listA和listB去重并集 = " + distinctList);
    }
}

【Java用法】java 8两个List集合取交集、并集、差集、去重并集_第1张图片

你可能感兴趣的:(java8合集,java,list,开发语言)