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 MapÂÂimportjava.io.*;importjava.util.stream.*;importjava.util.Arrays;importjava.util.Map;ÂÂclassGFG {   Â// Function to convert the string   Â// to the map   ÂpublicstaticMap 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 class   ÂprivateintuserId;   ÂprivateString name;   ÂprivateString city;   Â// Constructor   ÂpublicUser(intuserId, String name,               ÂString city)   Â{       Âthis.userId = userId;       Âthis.name = name;       Âthis.city = city;   Â}   Â// Getters of the user class   ÂpublicintgetUserId() {returnuserId; }   ÂpublicString getName() {returnname; }   ÂpublicString getCity() {returncity; }   Â// Overriding the toString method   Â// to return the custom string   Â@Override   ÂpublicString toString()   Â{       Âreturn"User [userId = "           Â+ userId +", name = "           Â+ name +", city = "           Â+ city +"]";   Â}}ÂÂclassGFG {   Â// Function to convert the User   Â// to the map   ÂpublicstaticMap 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 code   Âpublicstaticvoidmain(String[] args)   Â{       Â// Creating users       ÂUser 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 class   ÂprivateintuserId;   ÂprivateString name;   ÂprivateString city;   Â// Constructor of the User class   ÂpublicUser(intuserId, String name,               ÂString city)   Â{       Âthis.userId = userId;       Âthis.name = name;       Âthis.city = city;   Â}   Â// Getter functions   ÂpublicintgetUserId() {returnuserId; }   ÂpublicString getName() {returnname; }   ÂpublicString getCity() {returncity; }   Â// Overriding the toString() method   Â// to create a custom function   Â@Override   ÂpublicString toString()   Â{       Âreturn"User [userId = "           Â+ userId +", name = "           Â+ name +", city = "           Â+ city +"]";   Â}}ÂÂclassGFG {   Â// Function to convert the user   Â// object to the map   ÂpublicstaticMap 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 code   Âpublicstaticvoidmain(String[] args)   Â{       Â// Creating new users       ÂUser 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 class   ÂprivateintuserId;   ÂprivateString name;   ÂprivateString city;   Â// Constructor   ÂpublicUser(intuserId, String name,               ÂString city)   Â{       Âthis.userId = userId;       Âthis.name = name;       Âthis.city = city;   Â}   Â// Getter functions   ÂpublicintgetUserId() {returnuserId; }   ÂpublicString getName() {returnname; }   ÂpublicString getCity() {returncity; }   Â// Overriding the toString() method   Â// to create a custom function   Â@Override   ÂpublicString 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 code   Âpublicstaticvoidmain(String[] args)   Â{       Â// Creating new users       ÂUser 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}
