Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collect both matching and non-matching in one stream processing?

Tags:

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"?

like image 563
Torgeist Avatar asked Nov 14 '18 09:11

Torgeist


1 Answers

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); 
like image 87
Ravindra Ranwala Avatar answered Sep 17 '22 13:09

Ravindra Ranwala