$show=/label

Java 8 - Stream Group By - Collectors.GroupingBy() Examples

SHARE:

A complete guide to groupingby concept in java 8 and how to perform the group by operations using java 8 collectors api with example programs.

1. Overview

In this tutorial, We will learn how to perform the groupingby operation in java 8

If you have worked in the Oracle database, you must have seen the group by the operator in many complex SQL queries.

You will learn the following techniques in this lesson.

  • How to java stream group by operation?
  • Java stream group by count?
  • Java 8 stream group by and sort?
  • Java stream group by reduce?
  • java stream group by multiple fields?
  • group by with custom objects?

In a similar way, we can implement the group by clause from java 8 onwards. Java 8 Stream API is added with the data grouping capabilities as part of Collectors api.

Collectors API is to collect the final data from stream operations.

Java 8 - Stream Group By - Collectors.GroupingBy() Examples



2. Java 8 Collectors GroupingBy Syntax


groupingBy() method is an overloaded method with three methods.

This method returns a new Collector implementation with the given values.


public static <T,K> Collector<T,?,Map<K,List<T>>> groupingBy(Function<? super T,? extends K> classifier)


public static <T,K,A,D> Collector<T,?,Map<K,D>> groupingBy(Function<? super T,? extends K> classifier,
                                                           Collector<? super T,A,D> downstream)

public static <T,K,D,A,M extends Map<K,D>> Collector<T,?,M> groupingBy(Function<? super T,? extends K> classifier,
                                                                       Supplier<M> mapFactory,
                                                                       Collector<? super T,A,D> downstream)
 
Note:
Remember always group by operations returns a Map with the actual key and aggregated result as value.

3. Java 8 GroupingBy - Group by count


First, let us understand the simple group by operation to find the number of occurrences of each string from List.

package com.javaprogramto.java8.collectors.groupby;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class GroupingByCount {

	public static void main(String[] args) {

		// Creating List and adding duplicate values. 
		List<String> strings = new ArrayList<>();

		strings.add("Hello");
		strings.add("Ram");
		strings.add("Hello");
		strings.add("Sam");
		strings.add("Hello");
		strings.add("Yam");
		strings.add("Hello");
		strings.add("Raj");
		strings.add("Hello");
		strings.add("Raj");

		// Grouping by based on the count
		Map<String, Long> countMap = strings.stream()
				.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
		
		// printing the count of each string using groupingBy() 
		System.out.println("Count : "+countMap);
	}
}
 
Output:
Count : {Yam=1, Hello=5, Raj=2, Sam=1, Ram=1}

 
In the input list, the word Hello is repeated 5 times, Raj is for 2 times and reaming are for 1 time.

Group by operation is simplified using the new java 8 collectors api.

4. Java 8 - Grouping By and Sort


Next, Look at another example to sort the count operation.

package com.javaprogramto.java8.collectors.groupby;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;

public class GroupingByCountSort {

	public static void main(String[] args) {

		// Creating List and adding duplicate values.
		List<String> strings = new ArrayList<>();

		strings.add("Hello");
		strings.add("Ram");
		strings.add("Hello");
		strings.add("Sam");
		strings.add("Hello");
		strings.add("Yam");
		strings.add("Hello");
		strings.add("Raj");
		strings.add("Hello");
		strings.add("Raj");

		// Grouping by based on the count
		Map<String, Long> countMap = strings.stream()
				.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

		Map<String, Long> groupBySorted = countMap.entrySet().stream().sorted(Entry.comparingByValue())
				.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2, LinkedHashMap::new));

		// printing the count of each string and sorted
		System.out.println("Count sorted : " + groupBySorted);
	}
}
 
Output:
Count sorted : {Yam=1, Sam=1, Ram=1, Raj=2, Hello=5}
 
The output map is sorted by value in ascending order.

5. Java 8 Group by Sort Descending Order


// Descending Order
// Grouping by based on the count
Map<String, Long> countMap2 = strings.stream()
		.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

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

// Sort a map and add to finalMap
countMap2.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed())
		.forEachOrdered(e -> finalMapDescendingOrder.put(e.getKey(), e.getValue()));

System.out.println("Descending order sorted - " + finalMapDescendingOrder);

 
Output:

Descending order sorted - {Hello=5, Raj=2, Yam=1, Sam=1, Ram=1}

 

6. GroupingBy with List of Custom Objects


Let us create a custom class called Stock with name, quantity and price properties.

Create objects for Stock class and add them to the List.

Next, perform group by on stock name and sum quantity.

Stock.java

package com.javaprogramto.java8.collectors.groupby;

public class Stock {

	private String name;
	private int quantity;
	private double price;

	public Stock(String name, int quantity) {
		this.name = name;
		this.quantity = quantity;
	}

	public Stock(String name, int quantity, double price) {
		super();
		this.name = name;
		this.quantity = quantity;
		this.price = price;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

}

 
GroupingBy by Sum:

package com.javaprogramto.java8.collectors.groupby;

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

public class GroupingByCountObjects {

	public static void main(String[] args) {

		// Creating List and adding duplicate values.
		List<Stock> stocks = new ArrayList<>();

		stocks.add(new Stock("JP Morgan", 10));
		stocks.add(new Stock("ICICI", 10));
		stocks.add(new Stock("HDFC", 10));
		stocks.add(new Stock("ICICI", 10));
		stocks.add(new Stock("JP Morgan", 10));
		stocks.add(new Stock("JP Morgan", 10));

		// group by - stock name + sum(quanity)

		Map<String, Integer> noOfStocksByName = stocks.stream()
				.collect(Collectors.groupingBy(Stock::getName, Collectors.summingInt(Stock::getQuantity)));

		// printing the count of each string.
		System.out.println("No of stocks by stock name : " + noOfStocksByName);
	}
}
 
Output:
No of stocks by stock name : {ICICI=20, HDFC=10, JP Morgan=30}

 

7. GroupingBy by Multiple Fields


Next, apply the group by on multiple fields of Stock Name and Quantity. If these two fields are equal then get the count for no of stock objects.

package com.javaprogramto.java8.collectors.groupby;

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

public class GroupingByMultipleFields {

	public static void main(String[] args) {

		// Creating List and adding duplicate values.
		List<Stock> stocks = new ArrayList<>();

		stocks.add(new Stock("JP Morgan", 10, 100));
		stocks.add(new Stock("ICICI", 20, 100));
		stocks.add(new Stock("HDFC", 30, 300));
		stocks.add(new Stock("ICICI", 20, 200));
		stocks.add(new Stock("JP Morgan", 10, 100));
		stocks.add(new Stock("JP Morgan", 10, 100));

		// group by - stock name + quanity

		Map<String, Map<Integer, Long>> noOfStocksByName = stocks.stream()
				.collect(Collectors.groupingBy(Stock::getName, Collectors.groupingBy(Stock::getQuantity, Collectors.counting())));

		// printing the count of each string.
		System.out.println("Group by on multiple properties" + noOfStocksByName);
	}
}
 
Output:
Group by on multiple properties{ICICI={20=2}, HDFC={30=1}, JP Morgan={10=3}}

 

8. Conclusion


In this article, We have seen how to use group by function in java 8 collections.

Examples are shown to get the count, sort, sum on custom objects, group by on multiple fields.

And also we can modify the return Map value type, Getting the average, sum, minimum, maximum and Summary values from grouped results.



COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 - Stream Group By - Collectors.GroupingBy() Examples
Java 8 - Stream Group By - Collectors.GroupingBy() Examples
A complete guide to groupingby concept in java 8 and how to perform the group by operations using java 8 collectors api with example programs.
https://blogger.googleusercontent.com/img/a/AVvXsEh_RPLbx0oq_t-161648gsqp_Lgg9NeCnthhux2lrYPPKymlU97yvT0fbFWotIViDj6SGZeG7Hcz7dx3hE53mIUEs5U5N9AB8MNV8_wZ76A5AfiRIGcNr7VFtWm0PC5M-8bdUak6MBKZxOvBp-shfek0Or1KPZCxNoeToBoHfZ2hmF00UDziEUeNfrd=w400-h214
https://blogger.googleusercontent.com/img/a/AVvXsEh_RPLbx0oq_t-161648gsqp_Lgg9NeCnthhux2lrYPPKymlU97yvT0fbFWotIViDj6SGZeG7Hcz7dx3hE53mIUEs5U5N9AB8MNV8_wZ76A5AfiRIGcNr7VFtWm0PC5M-8bdUak6MBKZxOvBp-shfek0Or1KPZCxNoeToBoHfZ2hmF00UDziEUeNfrd=s72-w400-c-h214
JavaProgramTo.com
https://www.javaprogramto.com/2021/02/%20java-8-groupingby-collector.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2021/02/%20java-8-groupingby-collector.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content