$show=/label

Java 8 GroupingBy - Group by Modifying Map Value Type

SHARE:

How to modify the return type of Map value type for Collectors.groupingby(). Example program to change the Map value return type in java 8 stream.

1. Overview

In this tutorial, We will learn how to modify the Map value return type for the java 8 Grouping By operation.

In the previous article, we have seen how to perform Group by operation in java 8 with count, sum actions.

After calling the Collectors.groupingby() method it returns the Map<K, V> key and value

In some of the cases you may need to return the key type as List or Set.

Java 8 GroupingBy - Group by Modifying Map Value Type


2. Modify Map Value Type to List For GroupingBy Result

In the below program, we are trying to first find the count of each string from list. Returned map key type is String, value type is Long. 

Next, Let us see how to convert Long to List<String> to take all the values into List instead of getting the count.


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 GroupingByModifyValueType {

	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 type - <String, Long>
		Map<String, Long> countMap = strings.stream()
				.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

		// printing the count of each string.
		System.out.println("Count : " + countMap);

		// Grouping by - change the Map value type
		// Map type - <String, List<String>>
		Map<String, List<String>> mapValueType = strings.stream()
				.collect(Collectors.groupingBy(Function.identity(), Collectors.toList()));

		System.out.println("List group by : " + mapValueType);
	}
}
 

Output:

Count : {Yam=1, Hello=5, Raj=2, Sam=1, Ram=1}
List group by : {Yam=[Yam], Hello=[Hello, Hello, Hello, Hello, Hello], Raj=[Raj, Raj], Sam=[Sam], Ram=[Ram]}
 

3. Modify Map Value Type to Set For GroupingBy Result

From the above output we are seeing the duplicate values in the list, Next, we want to remove the duplicates from it. So, we need to instruct to the groupingBy() method use Set instead of List.


package com.javaprogramto.java8.collectors.groupby;

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

public class GroupingByModifyValueTypeSet {

	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 - change the Map value type
		// Map type - <String, Set<String>>
		Map<String, Set<String>> mapValueType = strings.stream()
				.collect(Collectors.groupingBy(Function.identity(), Collectors.toSet()));

		System.out.println("Set group by : " + mapValueType);
	}
}
 

Output:

Set group by : {Yam=[Yam], Hello=[Hello], Raj=[Raj], Sam=[Sam], Ram=[Ram]}
 

4. Modify Map value type to Custom Objects List or Set

As of now, we have shown example to work with the simple types. Now, Let us create a Trade class with name, quantity and purchased amount.

Let us get the group by stock name and its quantities from all stocks.

Trade.java

package com.javaprogramto.java8.collectors.groupby;

public class Trade {

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

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

	public Trade(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;
	}

	@Override
	public String toString() {
		return "Stock [ " + name + ", " + quantity + ", " + price + "]";
	}
}
 

Group By with trade name and List of quantities.

Normally, we perform the count, summing, min or max but now we need to collect the a value from Trade object into List.

Below example will modify the grouping by Map value type to List<Integer>.


package com.javaprogramto.java8.collectors.groupby;

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

public class GroupingByModifyCustomObjects {

	public static void main(String[] args) {

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

		Trades.add(new Trade("JP Morgan", 10));
		Trades.add(new Trade("ICICI", 20));
		Trades.add(new Trade("HDFC", 30));
		Trades.add(new Trade("ICICI", 40));
		Trades.add(new Trade("JP Morgan", 50));
		Trades.add(new Trade("JP Morgan", 60));

		// group by - Trade name + List<Integer> list of Quantity's

		Map<String, List<Integer>> noOfTradesByName 
			= Trades
				.stream()
				.collect(Collectors
				.groupingBy(Trade::getName, 
						Collectors.mapping(Trade::getQuantity, Collectors.toList())));

		// printing the count of each string.
		System.out.println("No of stocks by name in each trade: " + noOfTradesByName);
	}
}
 

Output:

No of stocks by name in each trade: {ICICI=[20, 40], HDFC=[30], JP Morgan=[10, 50, 60]}
 

We can change the type to Set using toSet() method also.


5. Conclusion

In this article, We have seen how to modify the Map value type for the group by result in java 8.

GitHub

How to convert List to Map in Java 8?

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 GroupingBy - Group by Modifying Map Value Type
Java 8 GroupingBy - Group by Modifying Map Value Type
How to modify the return type of Map value type for Collectors.groupingby(). Example program to change the Map value return type in java 8 stream.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3f4FkTESg5NQ8AiwHVJK3Kr94CoIkEUYp4iY-bzAKGogNCYJgsAboQuiFu4Lf4D5f8OY0aZig_oAwNr8TMkJmkuI6qbLohvKOD6B4y0NCiA4t83h9G6NHkSjqDzytTD5TpKgV3ra4SHo/w400-h296/Java+8+GroupingBy+-+Group+by+Modifying+Map+Value+Type.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh3f4FkTESg5NQ8AiwHVJK3Kr94CoIkEUYp4iY-bzAKGogNCYJgsAboQuiFu4Lf4D5f8OY0aZig_oAwNr8TMkJmkuI6qbLohvKOD6B4y0NCiA4t83h9G6NHkSjqDzytTD5TpKgV3ra4SHo/s72-w400-c-h296/Java+8+GroupingBy+-+Group+by+Modifying+Map+Value+Type.png
JavaProgramTo.com
https://www.javaprogramto.com/2021/02/%20java-8-groupingby-modify-map-value-type.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2021/02/%20java-8-groupingby-modify-map-value-type.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