Friday, December 27, 2024
Google search engine
HomeLanguagesJavaHow to convert a Stream into a Map in Java

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:

  1. KeyMapper: This function is used for extracting keys of the Map from stream value.
  2. 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
      
    import java.io.*;
    import java.util.stream.*;
    import java.util.Arrays;
    import java.util.Map;
      
    class GFG {
      
        // Function to convert the string
        // to the map
        public static Map toMap(String input)
        {
            Map<String, Integer> lengthMap
                = Arrays.stream(input.split(" "))
                      .collect(Collectors.toMap(
                          value
                          -> value,
                          value -> value.length()));
      
            return lengthMap;
        }
        public static void main(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:

    1. (value -> value): It reads the current stream value and returns it as the key of the Map.
    2. (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>
      
    import java.util.Arrays;
    import java.util.Map;
    import java.util.stream.*;
      
    // Implementing the User class
    public class User {
      
        // Attributes of the user class
        private int userId;
        private String name;
        private String city;
      
        // Constructor
        public User(int userId, String name,
                    String city)
        {
            this.userId = userId;
            this.name = name;
            this.city = city;
        }
      
        // Getters of the user class
        public int getUserId() { return userId; }
      
        public String getName() { return name; }
      
        public String getCity() { return city; }
      
        // Overriding the toString method
        // to return the custom string
        @Override
        public String toString()
        {
            return "User [userId = "
                + userId + ", name = "
                + name + ", city = "
                + city + "]";
        }
    }
      
    class GFG {
      
        // Function to convert the User
        // to the map
        public static Map 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));
      
            return userMap;
        }
      
        // Driver code
        public static void main(String[] args)
        {
      
            // Creating users
            User user1
                = new User(1, "User1", "Pune");
      
            User user2
                = new User(2, "User2", "Mumbai");
      
            User user3
                = new User(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>>
      
    import java.util.Arrays;
    import java.util.Map;
    import java.util.List;
    import java.util.stream.*;
      
    // Implementing the User class
    public class User {
      
        // Parameters of the user class
        private int userId;
        private String name;
        private String city;
      
        // Constructor of the User class
        public User(int userId, String name,
                    String city)
        {
            this.userId = userId;
            this.name = name;
            this.city = city;
        }
      
        // Getter functions
        public int getUserId() { return userId; }
      
        public String getName() { return name; }
      
        public String getCity() { return city; }
      
        // Overriding the toString() method
        // to create a custom function
        @Override
        public String toString()
        {
            return "User [userId = "
                + userId + ", name = "
                + name + ", city = "
                + city + "]";
        }
    }
      
    class GFG {
      
        // Function to convert the user
        // object to the map
        public static Map 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));
      
            return cityUserListMap;
        }
      
        // Driver code
        public static void main(String[] args)
        {
      
            // Creating new users
            User user1
                = new User(1, "User1", "Pune");
            User user2
                = new User(2, "User2", "Mumbai");
            User user3
                = new User(3, "User3", "Nagpur");
            User user4
                = new User(4, "User4", "Pune");
            User user5
                = new User(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>
      
    import java.util.Arrays;
    import java.util.Map;
    import java.util.stream.*;
      
    // Implementing the user class
    public class User {
      
        // Parameters of the user class
        private int userId;
        private String name;
        private String city;
      
        // Constructor
        public User(int userId, String name,
                    String city)
        {
            this.userId = userId;
            this.name = name;
            this.city = city;
        }
      
        // Getter functions
        public int getUserId() { return userId; }
      
        public String getName() { return name; }
      
        public String getCity() { return city; }
      
        // Overriding the toString() method
        // to create a custom function
        @Override
        public String toString()
        {
            return "User [userId = "
                + userId + ", name = "
                + name + ", city = "
                + city + "]";
        }
    }
      
    class GFG {
      
        public static Map 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()));
      
            return cityUserCountMap;
        }
      
        // Driver code
        public static void main(String[] args)
        {
      
            // Creating new users
            User user1
                = new User(1, "User1", "Pune");
            User user2
                = new User(2, "User2", "Mumbai");
            User user3
                = new User(3, "User3", "Nagpur");
            User user4
                = new User(4, "User4", "Pune");
            User user5
                = new User(5, "User5", "Mumbai");
      
            System.out.println(toMap(user1, user2,
                                     user3, user4,
                                     user5));
        }
    }

    
    
    Output:

    {Nagpur=1, Pune=2, Mumbai=2}
    
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments