How to intersect multiple sets?

vale4674 picture vale4674 · Oct 24, 2010 · Viewed 17.7k times · Source

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);
}

Answer

Jack picture Jack · Oct 24, 2010

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);