Classical set operations for java.util.Collection

JavaCollectionsSet

Java Problem Overview


Is there any built-in functionality for classical set operations on the java.util.Collection class? My specific implementation would be for ArrayList, but this sounds like something that should apply for all subclasses of Collection. I'm looking for something like:

ArrayList<Integer> setA ...
ArrayList<Integer> setB ...
ArrayList<Integer> setAintersectionB = setA.intersection(setB);
ArrayList<Integer> setAminusB = setA.subtract(setB);

After some searching, I was only able to find home-grown solutions. Also, I realize I may be confusing the idea of a "Set" with the idea of a "Collection", not allowing and allowing duplicates respectively. Perhaps this is really just functionality for the Set interface?

In the event that nobody knows of any built-in functionality, perhaps we could use this as a repository for standard practice Java set operation code? I imagine this wheel has been reinvented numerous times.

Java Solutions


Solution 1 - Java

Intersection is done with Collection.retainAll; subtraction with Collection.removeAll; union with Collection.addAll. In each case, as Set will act like a set and a List will act like a list.

As mutable objects, they operate in place. You'll need to explicitly copy if you want to retain the original mutable object unmutated.

Solution 2 - Java

I would recommend Google Guava. The Sets class seems to have exactly what you are looking for. It has a intersection method and a difference method.

This presentation is probably something you want to watch if you're interested. It refers to Google Collections, which was Guava's original name.

Solution 3 - Java

For mutable operations see accepted answer.

For an imutable variant you can do this with java 8

subtraction

set1
  .stream()
  .filter(item-> !set2.contains(item))
  .collect(Collectors.toSet())

intersection

set1
  .stream()
  .filter(item-> set2.contains(item))
  .collect(Collectors.toSet())

Solution 4 - Java

Are you looking for [java.util.Set](http://java.sun.com/javase/6/docs/api/java/util/Set.html "Set") interface (and its implementations HashSet and TreeSet (sorted))?
The interface defines removeAll(Collection c) which looks like substract(), and retainAll(Collection c) which looks like intersection.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRossView Question on Stackoverflow
Solution 1 - JavaTom Hawtin - tacklineView Answer on Stackoverflow
Solution 2 - JavaBenno RichtersView Answer on Stackoverflow
Solution 3 - JavamhstnscView Answer on Stackoverflow
Solution 4 - JavaPhiLhoView Answer on Stackoverflow