有没有办法在多个列表中找到共同元素?

问题描述 投票:0回答:9

我有一个整数数组列表。我需要找到它们之间的共同点。我能想到的是两个列表中的公共元素

中列出的内容的扩展
Example would be 
[1,3,5],
[1,6,7,9,3],
[1,3,10,11]

should result in [1,3]

数组中也没有重复项。

有没有直接的方法来做到这一点?

java arrays collections guava colt
9个回答
20
投票

您可以将列表转换为集合,然后使用

Set.retainAll
方法在不同集合之间进行交集。 一旦您将所有集合相交,您就剩下公共元素,并且您可以将结果集转换回列表。


14
投票

您可以使用Guava提供的Set交集方法,这是一个小例子:

public <T> Set<T> intersection(List<T>... list) {
    Set<T> result = Sets.newHashSet(list[0]);
    for (List<T> numbers : list) {
        result = Sets.intersection(result, Sets.newHashSet(numbers));
    }
    return result;
}

希望能帮到你


8
投票

我们可以使用Collections

retainAll方法。我用第一个数组列表初始化了我的 
commons
数组列表,并为每个剩余的数组列表调用它。

List<List<Integer>> lists = new ArrayList<List<Integer>>();
lists.add(new ArrayList<Integer>(Arrays.asList(1, 3, 5)));
lists.add(new ArrayList<Integer>(Arrays.asList(1, 6, 7, 9, 3)));
lists.add(new ArrayList<Integer>(Arrays.asList(1, 3, 10, 11)));

List<Integer> commons = new ArrayList<Integer>();
commons.addAll(lists.get(1));
for (ListIterator<List<Integer>> iter = lists.listIterator(1); iter.hasNext(); ) {
    commons.retainAll(iter.next());
}

System.out.println(commons);
System.out.println(lists.get(1));

6
投票

使用 Java 8

ArrayList retain = list1.stream()
                     .filter(list2::contains).filter(list3::contains).collect(toList())

1
投票

如果您正在寻找一个返回所有列表中存在的元素的函数,

那么直接简单的方法就是构建统计数据 { < member, occurences > }

这里的条件是同一个列表中不能有重复,

private Set<Integer> getCommonElements(ArrayList<Integer[]> idList)
{

    MapList<Integer,Short> stat = new MapList<Integer,Short>();

    // Here we count how many times each value occur
    for (int i = 0; i < idList.size(); i++)
    {
        for (int j = 0; j < idList.get(i).size; j++)
        {
            if (stat.containsKey(idList.get(i)[j]))
            {
                stat.set(idList.get(i)[j], stat.get(idList.get(i)[j])+1);
            }
            else
            {
                stat.add(idList.get(i)[j], 1);
            }
        }
    }

    // Here we only keep value that occured in all lists
    for (int i = 0; i < stat.size(); i++)
    {
        if (stat.get(i) < idList.size())
        {
            stat.remove(i);
            i--;
        }
    }

    return stat.keySet();
}

0
投票
public class ArrayListImpl{
  public static void main(String s[]){
    ArrayList<Integer> al1=new ArrayList<Integer>();
     al1.add(21);al1.add(23);al1.add(25);al1.add(26);
    ArrayList<Integer> al2=new ArrayList<Integer>();
     al2.add(15);al2.add(16);al2.add(23);al2.add(25);
     ArrayList Al3=new ArrayList<Integer>();
     al3.addAll(al1);
      System.out.println("Al3 Elements :"+al3);
     al3.retainAll(al2); //Keeps common elements of (al1 & al2) & removes remaining elements
       System.out.println("Common Elements Between Two Array List:"+al3);  
}
}

0
投票

如果您使用的是 JAVA 8 流。然后使用流归约操作我们可以实现相同的目的。

考虑你的例子:比方说 a = [1,3,5],b = [1,6,7,9,3] 和 c = [1,3,10,11]

List<Integer> commonElements = Stream.of(a,b,c)
     .reduce((s1,s2) -> {
          s1.retainAll(s2); 
          return s1;
      }).orElse(Collections.emptyList());

请记住,运行此操作后,

a
也将被修改为通用值。所以你会失去
a
的实际价值。

因此,运行此操作后,

a
的元素和
commonElements
的结果元素将基本相同。


0
投票

使用Set的retainAll功能给出另一种替代代码

public List getCommonItems(List... lists) {
    Set<Integer> result = new HashSet<>(lists[0]);

    for (List list : lists) {
        result.retainAll(new HashSet<>(list));
    }

    return new ArrayList<>(result);;
}

用途:

List list1 = [1, 2, 3]
List list2 = [3, 2, 1]
List list3 = [2, 5, 1]

List commonItems = getCommonItems(list1, list2, list3)
System.out.println("Common items: " + result);

结果:

commonItems: [1, 2]

-1
投票
public class commonvalue {

  
   Public static void MyMethod(){
        
       Set<integer> S1 = new set<integer>{1,3,5};
        Set<integer> S2 = new set<integer>{1,6,7,9,3};
        Set<integer> S3 = new set<integer>{1,3,10,11};
           
            s2.retainall(s1);
            s3.retainall(s2);
       
       system.debug(s3);
}
}
© www.soinside.com 2019 - 2024. All rights reserved.