Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

Is there a straight forward way to do this?

like image 980
ravindrab Avatar asked Mar 03 '13 08:03

ravindrab


People also ask

How do you find the common elements in multiple lists in python?

We can also apply the reduce function in python. This function is used to apply a given function passed onto it as argument to all of the list elements mentioned in the sequence passed along. The lambda function finds out the common elements by iterating through each nested list after set is applied to them .

How do you find the common elements of two lists?

Using & Operator The set's & operator is also one way of finding common elements in two lists. In this method, both the lists are converted into sets first and then the common elements are found using & . First both the lists are converted into set using set() function.

How do you find the common elements in two lists in Apex?

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. Save this answer.


1 Answers

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.

like image 97
Amir Kost Avatar answered Sep 24 '22 06:09

Amir Kost