简体   繁体   English

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

[英]Is there a way to find common elements in multiple lists?

I have a list of integer arrays. I need to find the common elements between those.我有一个 integer arrays 的列表。我需要找到它们之间的共同元素。 What I can think of is an extension of what is listed in Common elements in two lists我能想到的是两个列表中常见元素中列出的内容的扩展

Example would be 
[1,3,5],
[1,6,7,9,3],
[1,3,10,11]

should result in [1,3]

There are no duplicates in the arrays as well. arrays 中也没有重复项。

Is there a straight forward way to do this?有没有直接的方法来做到这一点?

You can transform the lists to sets, and then use Set.retainAll method for intersection between the different sets.您可以将列表转换为集合,然后使用Set.retainAll方法进行不同集合之间的交集。 Once you intersect all sets, you are left with the common elements, and you can transform the resulting set back to a list.一旦您将所有集合相交,就剩下公共元素,您可以将结果集合转换回列表。

You can use Set's intersection method offered by Guava , Here is a little example :您可以使用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;
}

Hope that could help you希望能帮到你

We can use retainAll method of Collections .我们可以使用Collections 的retainAll方法 I initialised my commons arraylist with the first array list and called this for each remaining arraylists.我用第一个数组列表初始化了我的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));

with Java 8使用 Java 8

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

If you are looking for a function that returns elements that exist in all lists,如果您正在寻找一个返回所有列表中存在的元素的函数,

then the straight forward & simple way is building a statistic { < member, occurences > }那么直接和简单的方法是建立一个统计{ <成员,出现次数> }

The condition here is no duplicates among the same list,这里的条件是同一个列表中没有重复,

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();
}
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);  
}
}
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);
}
}

If you are using JAVA 8 streams.如果您使用 JAVA 8 个流。 Then using stream reduce operation we can achieve the same.然后使用 stream reduce 操作我们可以达到同样的效果。

Considering your example: Let's say a = [1,3,5], b = [1,6,7,9,3] and c = [1,3,10,11]考虑你的例子:假设 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());

Keep in mind that after running this operation a will get modified with common values as well.请记住,在运行此操作后, a也会使用通用值进行修改。 So you will lose the actual value of a .所以你会失去a的实际价值。

So elements of a and the result elements of commonElements will be essentially the same after running this operation.因此a的元素和commonElements的结果元素在运行此操作后将基本相同。

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

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