简体   繁体   中英

Java many arraylists - find common element

I have an application that generates many arraylists, stored in a collection. All the arraylists will always have a common element.

I need to work out which is the common element. I managed this with two lists and using List.contains(...) but need to scale this to many lists.

How can I do this?

If you retainAll() all the List 's to a Set you will end up with all the common elements in the set.

Set set =  new HashSet();
for ( List list : yourLists ) 
{ 
    set.addAll( list );
} 
for ( List list : yourLists )
{
    set.retainAll( list );
}

This can almost trivially be optimized to only traverse the lists once (and use up heap space equal to the size of all the existing lists plus the additional size of the first list), but for illustrational purposes this version is better...

Cheers,

Use a hashtable that maps unique elements in each arraylist to its frequency (ie even if there are multiple occurrences of an element in the same arraylist it has to be incremented only once). Iterate through the hashtable until the value is equal to the number of arraylists. The corresponding key is the element we are looking for.

Use retainAll() so that at each step you will have intersection of lists

list1.retainAll(list2);
list1.retainAll(list3);

So this way list1 will be intersection of all the elements. Now if the common element is going to be duplicated then you need to add final list to Set and done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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