javasetintersection

How to intersect multiple sets?


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

Solution

  • retainAll

    Use Set#retainAll or List#retainAll() to get an intersection.

    To quote the Javadoc:

    Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.

    For example code using streams, see Answer by Chris.