Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intersect multiple sets?

Tags:

I have this list:

private List<Set<Address>> scanList; 

So my list contains multiple scans as you can see. After each scan I add new set into the list.

After all scans are finished I would like to take only the addresses that occur in every set and put it into:

private List<Address> addresses; 

Does something like this already exists in Set/TreeSet/HashSet?

EDIT: after answers, retainAll() is the right method. Thank you. Here is the source:

Set<Address> addressCross = scanList.get(0); for (int i = 1; i < scanList.size(); i++) {     addressCross.retainAll(scanList.get(i)); }    for (Address address : addressCross) {     addresses.add(address); } 
like image 896
vale4674 Avatar asked Oct 24 '10 16:10

vale4674


People also ask

How do you find the intersection of many sets in Python?

Python count intersection of sets To count the intersection of sets in Python, we will use “len(set(set1) & set(set2))”. Here, ” & “ is an intersection element common to both. It will return the count as “3” because “10, 8, and 6” are common to both the sets.

How do you work out the intersection of two sets?

The intersection of two or more given sets is the set of elements that are common to each of the given sets. The intersection of sets is denoted by the symbol '∩'. In the case of independent events, we generally use the multiplication rule, P(A ∩ B) = P( A )P( B ).


1 Answers

you can use retainAll(Collection<?> c), check it out here

A side note: that operation is called intersection.

To convert then it to a List you can use the method addAll(Collection<? extends E> c) which should work between all kinds of containers.

eg:

ArrayList<Address> list = new ArrayList<Address>(); list.addAll(yourSet); 
like image 79
Jack Avatar answered Sep 19 '22 08:09

Jack