简体   繁体   English

Collection.retainAll()匹配问题

[英]Collection.retainAll() matching issue

I am attempting to find the intersection between multiple collections of numbers. 我试图找到多个数字集合之间的交集。
For example, I want to find the intersection between the following 3 arrays of numbers: 例如,我要查找以下3个数字数组之间的交集:
a = {0,1,1} a = {0,1,1}
b = {1,1,2} b = {1,1,2}
c = {0,1,2} c = {0,1,2}
The result should be: 结果应为:
intersection(a,b,c) = {1} 相交(a,b,c)= {1}
but when I do it [sequentially] (see included code below) I get: intersection = {1,1}. 但是,当我按顺序执行此操作时(请参见下面的随附代码),我得到:交集= {1,1}。 What should I do differently such that I can get my desired result? 我应该怎样做才能获得理想的结果?

Thanks, 谢谢,
MGR 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);

使用Set作为交集而不是List

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM