How to group elements from a Stream.

The elements from a Stream class can be grouped in a Map using the collect method.

Syntax:

Map<key, List<Object>> map = stream.collect( Collectors.groupingBy( Object::methodKey ) );

Example:

In the following example, a Stream of Object Employee is created. The Employee class has a variable name. Then the stream is group according to the name of the employee. The collect method is called using Collectors.groupingBy, this way we have a Map with the employee name as the key. The Map is then written in System.out.

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) );
		
		// Group 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: {a=[a, a], b=[b, b], c=[c]}

References:

Lambda Expressions

Share this article:

Recent Comments