Java 8 – Stream Collectors groupBy examples

Category : Java | Sub Category : Java 8 Features | By Runner Dev Last updated: 2020-10-29 18:48:08 Viewed : 203


Java 8 – Stream Collectors groupBy examples  

Let we see how to use Java8 stream Collectors with groupby

 

Syntax:

<TKADCollector<T, ?, Map<KD>> java.util.stream.Collectors.groupingBy(Function<? super T, ? extends K> classifier, Collector<? super TAD> downstream)

Returns a Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

 

 

1. Group by a List , count and sort :

 

GroupingBy.java

 

 package java8features;

 

import java.util.Arrays;

import java.util.LinkedHashMap;

import java.util.List;

import java.util.Map;

import java.util.function.Function;

import java.util.stream.Collectors;

 

/**

 * @author prasadbonam

 *

 */

public class GroupingBy {

 

     public static void main(String[] args) {

 

           List<String> animals = Arrays.asList("Ant""Bat""Rat","Cat""Ant","Cat""Elephant""Cat""Dog","Dog");

 

           Map<String, Long> animalCountMap = animals.stream()

                     .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

           System.out.println("Animal Count :");

           System.out.println(animalCountMap);

          

           System.out.println("Animal Sorting Based on count:");

          

           Map<String, Long> sortingMap = new LinkedHashMap<>();

 

        //Sorting animals based on count

           animalCountMap.entrySet().stream()

                .sorted(Map.Entry.<String, Long>comparingByValue()

                        .reversed()).forEachOrdered(e -> sortingMap.put(e.getKey(), e.getValue()));

 

        System.out.println(sortingMap);

 

     }

 

}

 

  

Output:

Animal Count :

{Rat=1, Bat=1, Ant=2, Elephant=1, Cat=3, Dog=2}

Animal Sorting Based on count:

{Cat=3, Ant=2, Dog=2, Rat=1, Bat=1, Elephant=1}

 

 

2. “group by” a list of user defined Objects

2.1 Pojo class : ProductDO.java

 

 package java8features;

 

public class ProductDO {

 

     @Override

     public String toString() {

           return "ProductDO [prodId=" + prodId + ", prodName=" + prodName + ", prodQuantity=" + prodQuantity

                      + ", prodPrice=" + prodPrice + "]";

     }

 

     private int prodId;

     private String prodName;

     private int prodQuantity;

     private double prodPrice;

 

     public ProductDO(int prodId, String prodNameint prodQuantitydouble prodPrice) {

           this.prodId = prodId;

           this.prodName = prodName;

           this.prodQuantity = prodQuantity;

           this.prodPrice = prodPrice;

     }

  //getter/setters

}

 

 


 

2.2 Group by the  name, Count and Sum the Qty.

Java8GroupingBy.java

 

 package java8features;

 

import java.util.ArrayList;

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.util.stream.Collectors;

 

 

public class Java8GroupingBy {

 

     public static void main(String[] args) {

           List<ProductDO> productList = new ArrayList<>();

     // int prodId, String prodName, int prodQuantity, double prodPrice

     ProductDO prodDO = new ProductDO(111, "Mobile", 100, 50000.00);

     ProductDO prodDO1 = new ProductDO(121, "Fridge", 300, 20000.00);

     ProductDO prodDO2 = new ProductDO(131, "IceCream", 200, 30000.00);

     ProductDO prodDO3 = new ProductDO(141, "Pepsi", 600, 40000.00);

     ProductDO prodDO4 = new ProductDO(161, "Mobile", 100, 22000.00);

     ProductDO prodDO5 = new ProductDO(191, "Fridge", 200, 70000.00);

           productList.add(prodDO);

           productList.add(prodDO1);

           productList.add(prodDO2);

           productList.add(prodDO3);

           productList.add(prodDO4);

           productList.add(prodDO5);


   Map<String, Long> groupByProductNameCount = productList.stream()

                     .collect(Collectors.groupingBy(ProductDO::getProdName, Collectors.counting()));

           System.out.println("groupBy ProductName Count: ");

           System.out.println(groupByProductNameCount);

 

    Map<String, Long> groupByProdQtySum = productList.stream().collect(

                     Collectors.groupingBy(ProductDO::getProdName, Collectors.summingLong(ProductDO::getProdQuantity)));

           System.out.println("groupBy Product Quantiy Sum: ");

           System.out.println(groupByProdQtySum); 

         

           //group by product price

        Map<Double, List<ProductDO>> groupByProdPriceMap =

           productList.stream().collect(Collectors.groupingBy(ProductDO::getProdPrice));

        System.out.println("groupBy ProdPrice Map: ");

        System.out.println(groupByProdPriceMap);

 

           // group by product quantity

        Map<Integer, Set<String>> groupByProdPriceSet =

                productList.stream().collect(

                        Collectors.groupingBy(ProductDO::getProdQuantity,

                                Collectors.mapping(ProductDO::getProdName, Collectors.toSet())

                        )

                );

 

        System.out.println("groupBy Product quantity: ");

        System.out.println(groupByProdPriceSet);

       

     }

 

}

 

 

 


Output:

groupBy ProductName Count:

{Pepsi=1, IceCream=1, Mobile=2, Fridge=2}

 

groupBy Product Quantiy Sum:

{Pepsi=600, IceCream=200, Mobile=200, Fridge=500}

 

groupBy ProdPrice Map:

{70000.0=[ProductDO [prodId=191, prodName=Fridge, prodQuantity=200, prodPrice=70000.0]], 40000.0=[ProductDO [prodId=141, prodName=Pepsi, prodQuantity=600, prodPrice=40000.0]], 20000.0=[ProductDO [prodId=121, prodName=Fridge, prodQuantity=300, prodPrice=20000.0]], 22000.0=[ProductDO [prodId=161, prodName=Mobile, prodQuantity=100, prodPrice=22000.0]], 50000.0=[ProductDO [prodId=111, prodName=Mobile, prodQuantity=100, prodPrice=50000.0]], 30000.0=[ProductDO [prodId=131, prodName=IceCream, prodQuantity=200, prodPrice=30000.0]]}

 

groupBy Product quantity:

{100=[Mobile], 600=[Pepsi], 200=[IceCream, Fridge], 300=[Fridge]}

Search
Related Articles

Leave a Comment: