Java asymmetric set difference

If you need to find difference between two sets you can use method removeAll. The difference will be kept only on the set which is calling the method.


booleanremoveAll(Collection<?> c)


Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.

Parameters: c – collection containing elements to be removed from this set

Returns: true if this set changed as a result of the call

Important: In order removeAll to work the objects which will be inside of the sets must overwrite equals() and hashCode() method and give proper implementation related to the class! In my example I am using String which already has equals() and hashCode() implemented to be effective.

In this example we are creating two sets (set a and set b) with strings and we remove all common strings from set a which are also in set b

import java.util.HashSet;
import java.util.Set;

public class MainDifference {

    public static void main(String[] args) {
        Set<String> a = Set.of("A", "B", "C", "D", "E");
        Set<String> b = Set.of("M", "B", "N", "D", "O");
        // The difference will be "A", "C", "E" -> elements in "a" which are not in "b"

        // use copy constructor to get all values from Set "a"
        Set<String> result = new HashSet<>(a);

        // remove all elements from set "a" which are contained in set "b"



[A, C, E]

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.