Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream. all elements EXCEPT other elements

Tags:

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())) 
like image 877
Beta033 Avatar asked Feb 19 '16 18:02

Beta033


People also ask

How do I remove a particular element from a stream list?

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.

How do I skip the first element in a stream?

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.

How do you check if all values in list are same in Java?

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.


1 Answers

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); 
like image 89
rgettman Avatar answered Sep 18 '22 13:09

rgettman