$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,16,Arrays,16,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,28,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,93,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,35,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,13,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,105,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,104,java.lang,5,java.util. function,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,1,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,2,Math,1,Matrix,5,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,27,String,58,String Programs,12,String Revese,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,16,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://1.bp.blogspot.com/-_4INUY-q8uE/YBvYi3js7cI/AAAAAAAADPc/4OkIiBQOL0QPjp2pS4JfwtaQN901MF6sgCLcBGAsYHQ/w400-h296/Java%2B8%2BGroupingBy%2B-%2BGroup%2Bby%2BModifying%2BMap%2BValue%2BType.png
https://1.bp.blogspot.com/-_4INUY-q8uE/YBvYi3js7cI/AAAAAAAADPc/4OkIiBQOL0QPjp2pS4JfwtaQN901MF6sgCLcBGAsYHQ/s72-w400-c-h296/Java%2B8%2BGroupingBy%2B-%2BGroup%2Bby%2BModifying%2BMap%2BValue%2BType.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