How to partition elements from a Stream.

The elements from a Stream can be paritioned using Collectors.partitioningBy and a condition.

Syntax:

	Map<Boolean, List<Object>> map = stream.collect( Collectors.partitioningBy(s -> s.condition ) );

Example:

In the following code, a Stream of Object Student is created. The Student class has a name and a Grade variables. The stream is partitions depending on the grade of the Student. The collect method is called using Collectors.partitioningBy, Lambda is used to generate the condition. Here it is a grade >= to 80. The output map contains 2 entries one for the Objects passing the condition and the others.

Create the following java file:

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class LambdaStreamPartitionBy {

	public static void main(String[] argv){
		// Create the Stream
		Stream<Student> stream = Stream.of( new Student("a", 70), new Student("c", 80), new Student("a",90), new Student("b",100), new Student("b", 65) );
		
		// Partition the Elements 
		Map<Boolean, List<Student>> map = stream.collect( Collectors.partitioningBy(s -> s.getGrade() >= 80 ) );
		
		// Display the output
		System.out.println( "Produced Map: " + map );

		System.out.println( "Student with passing Grade: " + map.get( Boolean.TRUE ) );

	}

	static class Student {
		Student(String n, int w){
			name = n;
			grade = w;
		}
		
		String name;
		int grade;
		
		public String getName(){
			return name;
		}
		
		public int getGrade(){
			return grade;
		}
		
		public String toString(){
			return name;
		}
	}
	
}

The output will be:

Produced Map: {false=[a, b], true=[c, a, b]}
Student with passing Grade: [c, a, b]

References:

Lambda Expressions

Share this article:

Recent Comments