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

  • A+
Category:Languages

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); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: