Minus operation in java 8 for subtracting Lists
18,517
Solution 1
If you must use Streams :
List<Integer> diff = list1.stream()
.filter(i -> !list2.contains(i))
.collect (Collectors.toList());
Solution 2
Try this:
List<Integer> difference = new ArrayList<>(list1);
difference.removeAll(list2);
System.out.println("Remove: " + difference); //3
Solution 3
Using Apache commons:
CollectionUtils.subtract(list1, list2);
Pros: Very readable. Cons: No type safety
Author by
Manu Joy
Updated on June 23, 2022Comments
-
Manu Joy almost 2 years
Suppose I have two lists:
List<Integer> list1 = Arrays.asList(1, 2, 3); List<Integer> list2 = Arrays.asList(1, 2, 4, 5);
Now I want to perform
(list1 - list2)
. The expected ouptut is{3}
. How to do this using java 8 streams?