Collectors partitioningBy() method in Java 8

Java 8Object Oriented ProgrammingProgramming

The partioningBy() method returns a Collector that partitions the input elements according to a Predicate, and organizes them into a Map<Boolean, List<T>>.

The syntax is as follows.

static <T> Collector<T,?,Map<Boolean,List<T>>> partitioningBy(Predicate<? super T> predicate)

Here, the parameter,

  • T − Type of the input elements

  • predicate − For organizing input elements

To work with Collectors class in Java, import the following package.

import java.util.stream.Collectors;

The following is an example to implement partitioningBy() method in Java.

Example

 Live Demo

import java.util.Map;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<Integer> stream = Stream.of(25, 50, 75, 100, 125, 150);
      // true for stream element 50
      Map<Boolean, List<Integer>> m = stream.collect(Collectors.partitioningBy(a -> a == 50));
      System.out.println("Stream = "+ m);
   }
}

Output

Stream = {false=[25, 75, 100, 125, 150], true=[50]}
raja
Updated on 30-Jul-2019 22:30:25

Advertisements