Collectors.groupby example : How to do group by in java

We have already seen some examples on Collectors in previous post.  In this post, we are going to see Java 8 Collectors groupby example. Groupby is another feature added in java 8 and it is very much similar to SQL/Oracle.
Lets understand more with the help of example: Lets create our model class country as below:
package org.arpit.java2blog;
public class Country{
 String countryName; 
 long population;
 public Country() {
 public Country(String countryName,long population) {
  this.countryName = countryName;
 public String getCountryName() {
  return countryName;
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 public long getPopulation() {
  return population;
 public void setPopulation(long population) {
  this.population = population;
public int hashCode() {
 final int prime = 31;
 int result = 1;
 result = prime * result
   + ((countryName == null) ? 0 : countryName.hashCode());
 result = prime * result + (int) (population ^ (population >>> 32));
 return result;
public boolean equals(Object obj) {
 if (this == obj)
  return true;
 if (obj == null)
  return false;
 if (getClass() != obj.getClass())
  return false;
 Country other = (Country) obj;
 if (countryName == null) {
  if (other.countryName != null)
   return false;
 } else if (!countryName.equals(other.countryName))
  return false;
 if (population != other.population)
  return false;
 return true;
 public String toString()
  return "{"+countryName+","+population+"}";
Lets create main class in which we will use Collectors.groupBy to do group by.
package org.arpit.java2blog;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Java8CollectorsGroupBy {
 public static void main(String[] args) {

  List<Country> items = Arrays.asList(new Country("India", 20000),
    new Country("China", 40000), new Country("Nepal", 30000),
    new Country("India", 50000), new Country("China", 10000));
  // Group by countryName
  Map<String, List<Country>> groupByCountry =
  // Group by CountryName and calculates the count
  Map<String, Long> counting =
  // Group by countryName and sum up the population
  Map<String, Long> populationCount =

When you run above class, you will get below output:
[{India,20000}, {India,50000}]
{China=2, Nepal=1, India=2}
{China=50000, Nepal=30000, India=70000}

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012