Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minus operation in java 8 for subtracting Lists

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?

like image 247
Manu Joy Avatar asked Jun 22 '15 10:06

Manu Joy


People also ask

How to get difference between 2 lists in Java?

Using the Java List API. We can create a copy of one list and then remove all the elements common with the other using the List method removeAll(): List<String> differences = new ArrayList<>(listOne); differences. removeAll(listTwo); assertEquals(2, differences.

How to compare two list in Java using stream?

You need to override equals() method in SchoolObj class. contains() method you will uses the equals() method to evaluate if two objects are the same. But better solution is to use Set for one list and filter in another list to collect if contains in Set. Set#contains takes O(1) which is faster.


3 Answers

Try this:

List<Integer> difference = new ArrayList<>(list1);
difference.removeAll(list2);
System.out.println("Remove: " + difference); //3
like image 199
Hiren Avatar answered Oct 05 '22 11:10

Hiren


If you must use Streams :

List<Integer> diff = list1.stream()
                          .filter(i -> !list2.contains(i))
                          .collect (Collectors.toList());
like image 31
Eran Avatar answered Oct 05 '22 11:10

Eran


Using Apache commons:

CollectionUtils.subtract(list1, list2);

Pros: Very readable. Cons: No type safety

like image 45
Igal Avatar answered Oct 05 '22 09:10

Igal