首页 > 代码库 > Java 集合并交补

Java 集合并交补

示例

package com.example;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;public class ListOpt {    private List intersect(List ls1, List ls2) {        List list = new ArrayList(Arrays.asList(new Object[ls1.size()]));        Collections.copy(list, ls1);        list.retainAll(ls2);        return list;    }    private List union(List ls1, List ls2) {        List list = new ArrayList(Arrays.asList(new Object[ls1.size()]));        Collections.copy(list, ls1);        list.addAll(ls2);        return list;    }    private List diff(List ls1, List ls2) {        List list = new ArrayList(Arrays.asList(new Object[ls1.size()]));        Collections.copy(list, ls1);        list.removeAll(ls2);        return list;    }    public static void main(String[] args) {        List<Integer> l1 = new ArrayList<Integer>() {{            add(1);            add(2);            add(3);        }};        List<Integer> l2 = new ArrayList<Integer>() {{            add(2);            add(3);            add(4);        }};        ListOpt opt = new ListOpt();        List intersectList = opt.intersect(l1, l2);        List union = opt.union(l1, l2);        List diff = opt.diff(l1, l2);        print(intersectList);        print(union);        print(diff);    }    private static void print(List lst) {        if (lst.size() == 0) {            return;        }        for (int i = 0; i <lst.size(); ++i) {            System.out.println(lst.get(i));        }        System.out.println("---");    }}

输出

23---123234---1---

在操作之前对原对象进行了拷贝,如果对原对象直接操作会修改原来的对象

Java 集合并交补