This post will discuss how to calculate differences between two lists x and y in Java. The solution should return all elements present in x that are not present in y.

1. Using Collection.removeAll() method

The removeAll() method is used to remove all list elements that are contained in the specified collection. We can use it to calculate differences between two lists, as follows. To avoid modifications to the original list, create a copy of the first list before calling the removeAll() method.

Download  Run Code

Output:

[2, 4]

 
The following solution transforms the List into a Set and calls the removeAll() method on it.

Download  Run Code

Output:

[2, 4]

2. Using List.contains() method

In Java 8 and above, you can create a stream from the elements of the first list, and then filter the elements that are missing in the other list using the contains() method. This is demonstrated below:

Download  Run Code

Output:

[2, 4]

3. Using Apache Commons Collections

If you use the Apache Commons Collections library in your project, you may use the CollectionUtils’s subtract() method for this task.

Be vigilant with this utility method, as it might not remove all occurrences of an element from the list and depends on the cardinality of each element to find the difference. This behavior is demonstrated below:

Download Code

Output:

[2, 3, 4, 1]

That’s all about calculating differences between two lists in Java.