How to convert a Stream into a Map in Java

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
In this article, the methods to convert a stream into a map is discussed.
Method 1: Using Collectors.toMap() Function
The Collectors.toMap() method takes two parameters as the input:
- KeyMapper: This function is used for extracting keys of the Map from stream value.
- ValueMapper: This function used for extracting the values of the map for the given key.
The following are the examples of the toMap function to convert the given stream into a map:
- Example 1: Here, we will convert a string into a Map with the keys as the words of the string and the value as the length of each word.
// Program to convert// the Stream to Mapimportjava.io.*;importjava.util.stream.*;importjava.util.Arrays;importjava.util.Map;classGFG {// Function to convert the string// to the mappublicstaticMap toMap(String input){Map<String, Integer> lengthMap= Arrays.stream(input.split(" ")).collect(Collectors.toMap(value-> value,value -> value.length()));returnlengthMap;}publicstaticvoidmain(String[] args){String input ="Geeks for Geek";System.out.println(toMap(input));}}Output:{Geek=4, for=3, Geeks=5}In the above example, the toMap collector takes two lambda functions as parameters:
- (value -> value): It reads the current stream value and returns it as the key of the Map.
- (value -> value.length): It reads the current stream value, finds its length and returns the value to the Map for the given key.
- Example 2: Now, lets use the toMap function to perform a bit more complex map conversion. Here, we will convert a list of users into a map where UserId is the key and the User is the value.
// Program to convert User[] into// Map<userId, User>importjava.util.Arrays;importjava.util.Map;importjava.util.stream.*;// Implementing the User classpublicclassUser {// Attributes of the user classprivateintuserId;privateString name;privateString city;// ConstructorpublicUser(intuserId, String name,String city){this.userId = userId;this.name = name;this.city = city;}// Getters of the user classpublicintgetUserId() {returnuserId; }publicString getName() {returnname; }publicString getCity() {returncity; }// Overriding the toString method// to return the custom string@OverridepublicString toString(){return"User [userId = "+ userId +", name = "+ name +", city = "+ city +"]";}}classGFG {// Function to convert the User// to the mappublicstaticMap toMap(User user1, User user2,User user3){Map<Integer, User> userMap= Arrays.asList(user1, user2, user3).stream().collect(Collectors.toMap(user-> user.getUserId(),user -> user));returnuserMap;}// Driver codepublicstaticvoidmain(String[] args){// Creating usersUser user1=newUser(1,"User1","Pune");User user2=newUser(2,"User2","Mumbai");User user3=newUser(3,"User3","Nagpur");System.out.println(toMap(user1, user2,user3));}}Output:{1=User [userId = 1, name = User1, city = Pune], 2=User [userId = 2, name = User2, city = Mumbai], 3=User [userId = 3, name = User3, city = Nagpur]}
Method 2: Using Collectors
The groupingBy collector takes one function as input and creates a group of stream objects using that function. The following are the examples to convert a stream into a map using groupingBy collector.
- Example 1: In this example, we will convert a user stream into a map whose key is the city and the value is the users living in that city.
// Java program to convert the User[]// into Map<city, List<User>>importjava.util.Arrays;importjava.util.Map;importjava.util.List;importjava.util.stream.*;// Implementing the User classpublicclassUser {// Parameters of the user classprivateintuserId;privateString name;privateString city;// Constructor of the User classpublicUser(intuserId, String name,String city){this.userId = userId;this.name = name;this.city = city;}// Getter functionspublicintgetUserId() {returnuserId; }publicString getName() {returnname; }publicString getCity() {returncity; }// Overriding the toString() method// to create a custom function@OverridepublicString toString(){return"User [userId = "+ userId +", name = "+ name +", city = "+ city +"]";}}classGFG {// Function to convert the user// object to the mappublicstaticMap toMap(User user1,User user2,User user3,User user4,User user5){Map<String, List<User> >cityUserListMap= Arrays.asList(user1, user2, user3,user4, user5).stream().collect(Collectors.groupingBy(User::getCity));returncityUserListMap;}// Driver codepublicstaticvoidmain(String[] args){// Creating new usersUser user1=newUser(1,"User1","Pune");User user2=newUser(2,"User2","Mumbai");User user3=newUser(3,"User3","Nagpur");User user4=newUser(4,"User4","Pune");User user5=newUser(5,"User5","Mumbai");System.out.println(toMap(user1, user2,user3, user4,user5));}}Output:{Nagpur=[User [userId = 3, name = User3, city = Nagpur]], Pune=[User [userId = 1, name = User1, city = Pune], User [userId = 4, name = User4, city = Pune]], Mumbai=[User [userId = 2, name = User2, city = Mumbai], User [userId = 5, name = User5, city = Mumbai]]}
- Example 2: We can also provide an additional collector to the groupingBy if we need some extra information than the actual object. In this example, we will see how to get the count of the users belonging to each city.
// Java program to convert User[]// into Map<city, countOfUser>importjava.util.Arrays;importjava.util.Map;importjava.util.stream.*;// Implementing the user classpublicclassUser {// Parameters of the user classprivateintuserId;privateString name;privateString city;// ConstructorpublicUser(intuserId, String name,String city){this.userId = userId;this.name = name;this.city = city;}// Getter functionspublicintgetUserId() {returnuserId; }publicString getName() {returnname; }publicString getCity() {returncity; }// Overriding the toString() method// to create a custom function@OverridepublicString toString(){return"User [userId = "+ userId +", name = "+ name +", city = "+ city +"]";}}classGFG {publicstaticMap toMap(User user1,User user2,User user3,User user4,User user5){Map<String, Long>cityUserCountMap= Arrays.asList(user1, user2, user3,user4, user5).stream().collect(Collectors.groupingBy(User::getCity,Collectors.counting()));returncityUserCountMap;}// Driver codepublicstaticvoidmain(String[] args){// Creating new usersUser user1=newUser(1,"User1","Pune");User user2=newUser(2,"User2","Mumbai");User user3=newUser(3,"User3","Nagpur");User user4=newUser(4,"User4","Pune");User user5=newUser(5,"User5","Mumbai");System.out.println(toMap(user1, user2,user3, user4,user5));}}Output:{Nagpur=1, Pune=2, Mumbai=2}



