Is there a way to find common elements in multiple lists? Is there a way to find common elements in multiple lists? arrays arrays

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


You can transform the lists to sets, and then use Set.retainAll method for intersection between the different sets.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 :

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. I initialised my commons arraylist with the first array list and called this for each remaining arraylists.

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