0

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?

0

3 Answers 3

2

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,

Sign up to request clarification or add additional context in comments.

2 Comments

I'm looking at this option, but as the set is unordered how do I determine the least common element (i.e. found lowest down all the lists)?
By definition all the elements in the set will occur in all the lists an equal number of times, (namely the list count). If even one of the elements occurred in one less list than the rest, it would not be included in the final set, would it?
1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.