Harry
Harry

Reputation: 63

How to find common elements in multiple lists?

I have a list of list (nest list). I need to find the common elements between those.

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

should result in [1,3]

If not using the retainAll method of HashSet, how to iterate all the element to find?

Thanks,

Upvotes: 4

Views: 2683

Answers (3)

RONAK TOSHNIWAL
RONAK TOSHNIWAL

Reputation: 81

This code is written in Apex(similar to java)

List<Integer> a = new List<Integer>{1,4,7,8};
List<Integer> b = new List<Integer>{2,5,3,6,4,8,9};
List<Integer> c = new List<Integer>{9,5,2,7,4};


for(integer i=0;i<a.size();i++){
    if(b.contains(a[i]) && c.contains(a[i])) {
        system.debug(a[i]);
    }
}

Output will be 4

Upvotes: 0

Narendra Jaggi
Narendra Jaggi

Reputation: 1338

Do the sorting on individual list which will result in following result,for Sorting you can use any merge sort for O(n(log (n))) complexity

list1 --> [1,3,5]
list2 --> [1,3,6,7,9]
list3 --> [1,3,10,11]

Once sorted use the outer loop for the list having minimum number of elements,and search in list2 and list3.
for eg
pick 2 item from list1 to search,
search in list2 up to , either the list exhausts or matching element is found , if element is found search in list3 other wise pick the 3 item from list1 i.e 5 to search.

Upvotes: 0

Jean Logeart
Jean Logeart

Reputation: 53819

What you can do:

Set<Integer> intersection = new HashSet<>(lists.get(0))
for(List<Integer> list : lists) {
    Set<Integer> newIntersection = new HashSet<>();
    for(Integer i : list) {
        if(intersection.contains(i)) {
            newIntersections.add(i);
        }
    }
    intersection = newIntersection;
}

Upvotes: 4

Related Questions