获取在Java中使用多种的retainAll列表的交集 [英] Get intersection of several Lists using retainAll in Java
问题描述
我有麻烦得到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);
和我得到这个结果:
list1的:[2,2 2,2]
list1: [2, 2, 2, 2]
不过我倒是希望得到这一个:
But I'd expect to get this one:
list1的:[2]
list1: [2]
...因为唯一的元素的所有列表份额的有一个的2,而不是的四的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列表的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!