Java 8 Streams Java Java API
The static overloaded methods Collectors#partitioningBy return a Collector which produces a Map when used with Stream#collect() method. The output map has keys of type Boolean, so there would be only two possible entries in the map, having keys: 'true' or 'false'.
The values of the map is a java.util.List of the stream elements.
<T> Collector<T,?,Map<Boolean,List<T>>> partitioningBy(Predicate<? super T> predicate)
<T,D,A> Collector<T,?,Map<Boolean,D>> partitioningBy(Predicate<? super T> predicate,
Collector<? super T,A,D> downstream)
Parameters
predicate: The return boolean from this predicate is populated as keys of the output map.
downstream: This Collector transforms values of the map from T to D.
Examples
This example partitions the streams integers into a map of even and odd numbers package com.logicbig.example.collectors;
import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream;
public class PartitioningByExample { public static void main (String[] args) { Map<Boolean, List<Long>> m = IntStream.range(1, 10) .mapToObj(Long::new) .collect(Collectors.partitioningBy( i -> i % 2 == 0)); System.out.println(m);
} }
Output{false=[1, 3, 5, 7, 9], true=[2, 4, 6, 8]}
Original Post
This example partitions the input strings into a map of strings values based on whether the first character is upper case or lower case. The downstream Collector converts the values list into the count (size of the list) package com.logicbig.example.collectors;
import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream;
public class PartitioningByExample2 { public static void main (String[] args) { Stream<String> s = Stream.of("Ace", "heart", "Club", "diamond"); Map<Boolean, Long> m = s.collect(Collectors.partitioningBy( x -> Character.isUpperCase(x.charAt(0)), Collectors.counting())); System.out.println(m); } }
Output{false=2, true=2}
Original Post
|