Minus operation in Java 8 for subtracting lists

Let's say 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 execute (list1 - list2)

. Expected output {3}

. How can I do this using java 8 streams?

+6


source to share


3 answers


If you must use Streams:



List<Integer> diff = list1.stream()
                          .filter(i -> !list2.contains(i))
                          .collect (Collectors.toList());

      

+13


source


Try it:



List<Integer> difference = new ArrayList<>(list1);
difference.removeAll(list2);
System.out.println("Remove: " + difference); //3

      

+9


source


Using Apache Commons:

CollectionUtils.subtract(list1, list2);

      

Pros: Very readable. Cons: no type safety

0


source







All Articles