Site icon

groupBy, mapping & statistics features in Java8 lambda stream (examples)

  1. Given a list of Person objects (POJOs).
  2. We would like to group person objects by their gender.
    • Group person objects by Male & Female.
  3. We will also apply mapping & statistics features on list of person objects.

1. Apply groupBy, mapping & statistics features on person POJOs

  1. Group person objects by gender i.e Male and Female
    • Get the List of person objects (Categorized by gender)
  2. Group persons by gender i.e Male and Female
    • Get the Set of person objects
  3. Group persons by gender i.e Male and Female
    • Get the  Set of names (of person) objects instead of complete person objects
  4. Count person objects by gender
    • Number of females and males in person objects
  5. Group person objects by gender and get person with max age
    • Max age of male and female persons
  6. Group person objects by gender and generate age statistics
    • Generate age statistics of person objects
    • Get avg, min and max age etc of male and female objects

2. Program – groupBy, mapping & statistics features (java8 lambda stream)

2.1.) Person Class:

package org.learn.GroupByJava8;

public class Person {
	public String name;
	public int age;
	public String gender;
	public Person(String name, int age, String gender) {
		this.name = name;
		this.age = age;
		this.gender = gender;
	}
	public String toString() {
	    return "[" + name + " " + age + " " +gender +"]";
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	
}

2.2 GroupByJava8 Class:

The GroupByJava8 example is as follows:

package org.learn.GroupByJava8;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class GroupByJava8
{
    public static void main( String[] args )
    {
    	List <Person> personList = new ArrayList<Person>();
		personList.add(new Person("Sharon", 21, "Female"));
		personList.add(new Person("Maria", 18,  "Female"));
		personList.add(new Person("Jack", 21 ,"Male"));
		personList.add(new Person("James", 35,  "Male"));		
		
		Map<String, List<Person>> groupByGenderList = 
				personList.stream().collect(Collectors.groupingBy(Person::getGender));
		
		//Group by gender List : Female-> Persons and Male -> Persons
		System.out.println("1. Group persons by gender - get result in List: ");
		System.out.println(groupByGenderList.toString());

		Map<String, Set<Person>> groupByGenderSet = 
				personList.stream().collect(Collectors.groupingBy(Person::getGender,Collectors.toSet()));
		
		//Group by gender Set: Female-> Persons and Male -> Persons
		System.out.println("2. Group persons by gender - get result in Set: ");
		System.out.println(groupByGenderSet.toString());
		
		Map<String, Set<String>> groupByGenderAndFirstNameSet
        = personList.stream().collect(Collectors.groupingBy(Person::getGender, TreeMap::new,
        		Collectors.mapping(Person::getName, Collectors.toSet())));    
		System.out.println("3. Group person by gender and get name of person - get result in Set: ");
		System.out.println(groupByGenderAndFirstNameSet.toString());
		
		Map<String, Long> countPersonByGender = personList.stream().
				collect(Collectors.groupingBy(Person::getGender,Collectors.counting()));
		
		System.out.println("4. Count person objects by gender: ");
		System.out.println(countPersonByGender.toString());		

		Map<String, Optional<Person>> personByMaxAge = personList.stream().
				collect(Collectors.groupingBy(Person::getGender
						,Collectors.maxBy(Comparator.comparing(Person::getAge))));		
		System.out.println("5. Group person objects by gender and get person with max age: ");
		System.out.println(personByMaxAge.toString());

		Map<String, IntSummaryStatistics> groupPersonsByAge = personList.stream().
				collect(Collectors.groupingBy(Person::getGender
						,Collectors.summarizingInt(Person::getAge)));		
		System.out.println("6. Group person objects by gender and get age statistics: ");
		System.out.println(groupPersonsByAge.toString());
		IntSummaryStatistics malesAge = groupPersonsByAge.get("Male");
		System.out.println("Avgerage male age:"+ malesAge.getAverage());
		System.out.println("Max male age:"+ malesAge.getMax());
		System.out.println("Min male age:"+ malesAge.getMin());
    }    
}

3. Output: groupBy, mapping & IntSummaryStatistics features in java8

1. Group persons by gender - get result in List: 
{Male=[[Jack 21 Male], [James 35 Male]], Female=[[Sharon 21 Female], [Maria 18 Female]]}
2. Group persons by gender - get result in Set: 
{Male=[[James 35 Male], [Jack 21 Male]], Female=[[Maria 18 Female], [Sharon 21 Female]]}
3. Group person by gender and get name of person - get result in Set: 
{Female=[Sharon, Maria], Male=[James, Jack]}
4. Count person objects by gender: 
{Male=2, Female=2}
5. Group person objects by gender and get person with max age: 
{Male=Optional[[James 35 Male]], Female=Optional[[Sharon 21 Female]]}
6. Group person objects by gender and get age statistics: 
{Male=IntSummaryStatistics{count=2, sum=56, min=21, average=28.000000, max=35}, 

Female=IntSummaryStatistics{count=2, sum=39, min=18, average=19.500000, max=21}}
Avgerage male age:28.0
Max male age:35
Min male age:21
Exit mobile version