Collection.retainAll()匹配问题

时间:2018-09-30 08:06:42

标签: java collections set-intersection

我正在尝试找到多个数字集合之间的交集。
例如,我想找到以下3个数字数组之间的交集:
a = {0,1,1}
b = {1,1,2}
c = {0,1,2}
结果应为:
相交(a,b,c)= {1}
但是,当我按顺序执行此操作时(请参见下面的随附代码),我得到:相交= {1,1}。我应该怎样做才能获得理想的结果?

谢谢,
MGR

ArrayList<Integer> a = new ArrayList<>(Arrays.asList(new Integer[] {0,1, 1}));
    ArrayList<Integer> b = new ArrayList<>(Arrays.asList(new Integer[]{2, 1, 1}));
    ArrayList<Integer> c = new ArrayList<>(Arrays.asList(new Integer[]{0,2,1}));

    ArrayList<Integer> intersection = a;
    /*System.out.println("intersection is "+intersection);
    System.out.println("b is\t"+b);
    System.out.println("A and B");*/
    //System.out.println(intersection.retainAll(b));
    intersection.retainAll(b);
    System.out.println("intersection now is "+intersection);
    /*System.out.println(intersection==null);
    System.out.println(intersection.isEmpty());
    System.out.println("Doing c:");
    System.out.println("c is\t"+c);
    System.out.println(intersection.retainAll(c));*/
    intersection.retainAll(c);
    System.out.println("intersection is "+intersection);

1 个答案:

答案 0 :(得分:0)

使用Set而不是List进行交点:

Set<Integer> intersection = new HashSet<>(a);