Java中使用retainAll获取多个List的交集 [英] Get intersection of several Lists using retainAll in Java

查看:105
本文介绍了Java中使用retainAll获取多个List的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在获取 Java 上的多个列表的交集时遇到了麻烦.我正在做的是这样的:我得到(可以说)3 个整数列表:

I'm having troubles to get the intersection of several Lists on Java. What I'm doing is this: I get (lets say) 3 Lists of integer numbers:

列表 1: [2, 2, 2, 2, 5, 5]

list 1: [2, 2, 2, 2, 5, 5]

列表 2:[2, 2, 103]

list 2: [2, 2, 103]

列表 3:[2, 431]

list 3: [2, 431]

我正在使用剩余的每个列表将 retainAll 应用于第一个列表:

I'm applying retainAll to the first one using each of the remaining lists:

list1.retainAll(list2);
list1.retainAll(list3);

我得到了这个结果:

列表 1: [2, 2, 2, 2]

list1: [2, 2, 2, 2]

但我希望得到这个:

列表 1:[2]

...因为所有列表共享的唯一元素是 one 2 而不是 four 2.

...Since the only element all lists share is one 2 and not four 2.

我知道这可能是retainAll函数的预期行为,但我需要得到我上面提到的结果.

I know this is probably the expected behaviour of the retainAll function, but I need to get the result I mentioned above.

有什么帮助吗?

使用 HashSet 禁止重复也不起作用.在这种情况下,例如:

Using a HashSet to disallow duplicates won't do the trick either. In this case, for instance:

列表 1: [2, 2, 2, 2, 5, 5]

list 1: [2, 2, 2, 2, 5, 5]

列表 2:[2, 2, 103]

list 2: [2, 2, 103]

列表 3:[2, 2, 2, 431]

list 3: [2, 2, 2, 431]

我需要得到以下结果:

列表 1: [2, 2] (因为所有列表都至少有一对 2)

list 1: [2, 2] (since all lists have at least a pair of 2's)

代替

列表 1:[2]

推荐答案

这个方法怎么样:

public static <T> Collection <T> intersect (Collection <? extends T> a, Collection <? extends T> b)
{
    Collection <T> result = new ArrayList <T> ();

    for (T t: a)
    {
        if (b.remove (t)) result.add (t);
    }

    return result;
}

public static void main (String [] args)
{
    List <Integer> list1 = new ArrayList <Integer> (Arrays.<Integer>asList (2, 2, 2, 2, 5, 5));
    List <Integer> list2 = new ArrayList <Integer> (Arrays.<Integer>asList (2, 2, 103));
    List <Integer> list3 = new ArrayList <Integer> (Arrays.<Integer>asList (2, 431));

    System.out.println (intersect (list1, intersect (list2, list3)));
}

这篇关于Java中使用retainAll获取多个List的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆