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); }
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.
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 ).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With