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

Torgeist :

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

Ravindra Ranwala :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35336&siteId=1