Is there a way to collect both matching and not matching elements of stream in one processing? Take this example:
final List<Integer> numbers = Arrays.asList( 1, 2, 3, 4, 5 ); final List<Integer> even = numbers.stream().filter( n -> n % 2 == 0 ).collect( Collectors.toList() ); final List<Integer> odd = numbers.stream().filter( n -> n % 2 != 0 ).collect( Collectors.toList() );
Is there a way to avoid running through the list of numbers twice? Something like "collector for matches and collector for no-matches"?
You may do it like so,
Map<Boolean, List<Integer>> oddAndEvenMap = numbers.stream() .collect(Collectors.partitioningBy(n -> n % 2 == 0)); final List<Integer> even = oddAndEvenMap.get(true); final List<Integer> odd = oddAndEvenMap.get(false);
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