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?
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.
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.
Try this:
List<Integer> difference = new ArrayList<>(list1);
difference.removeAll(list2);
System.out.println("Remove: " + difference); //3
If you must use Streams :
List<Integer> diff = list1.stream()
.filter(i -> !list2.contains(i))
.collect (Collectors.toList());
Using Apache commons:
CollectionUtils.subtract(list1, list2);
Pros: Very readable. Cons: No type safety
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With