I'm interested in identifying an approach that returns a list of elements excluding the elements in another list.
for example
List<Integer> multiplesOfThree = ... // 3,6,9,12 etc List<Integer> evens = ... // 2,4,6,8 etc List<Integer> others = multiplesOfThree.except(evens) // should return a list of elements that are not in the other list
how do you do this? i found an approach that's a bit clunky and difficult to read....
multiplesOfThree.stream() .filter(intval -> evens.stream().noneMatch(even -> even.intValue() == intval.intValue()))
Once we've finished operating on the items in the stream, we can remove them using the same Predicate we used earlier for filtering: itemList. removeIf(isQualified); Internally, removeIf uses an Iterator to iterate over the list and match the elements using the predicate.
Stream skip(n) method is used to skip the first 'n' elements from the given Stream. The skip() method returns a new Stream consisting of the remaining elements of the original Stream, after the specified n elements have been discarded in the encounter order.
allMatch() method. The allMatch() method returns true if all elements of the stream matches with the given predicate. It can be used as follows to check if all elements in a list are the same.
You can use Stream
's filter
method, passing a Predicate
that ensures that the element doesn't exist in evens
.
List<Integer> others = multiplesOfThree.stream() .filter(i -> !evens.contains(i)) .collect(Collectors.toList());
But assuming you have a mutable List
(e.g. ArrayList
), you don't even need streams, just Collections'
s removeAll
method.
multiplesOfThree.removeAll(evens);
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