Stream

Java Joy: Partition Stream By Predicate

Posted on by  
Hubert Klein Ikkink

The Java Stream API has many useful methods. If we want to partition a stream of objects by a given predicate we can use the partitioningBy() method from the java.util.stream.Collectors package. We must use this method in the collect() method of the stream. The result is a Map with the keys true and false. The objects from the stream that are true for the predicate will end up in the true value list and if the result of the predicate is false the value will end up in the list of values for the false key. The partitionBy method accepts a collector as second parameter. This collector will be applied to the values before they are put in the true or false keys in the result.

In the following example we use the partitioningBy method with different streams:

Continue reading →

shadow-left