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

ravindrab picture ravindrab · Mar 3, 2013 · Viewed 37.3k times · Source

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?

Answer

Amir Kost picture Amir Kost · Mar 3, 2013

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.