當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Stream轉Map用法及代碼示例


在 Java 8 中引入的 Stream API 用於處理對象的集合。流是支持各種方法的對象序列,這些方法可以流水線化以產生所需的結果。

在本文中,將討論將流轉換為Map的方法。

方法一:使用Java Collectors toMap()用法及代碼示例函數

Collectors.toMap() 方法將兩個參數作為輸入:

  1. KeyMapper:該函數用於從流值中提取 Map 的鍵。
  2. ValueMapper:此函數用於提取給定鍵的映射值。

以下是 toMap 函數將給定流轉換為Map的示例:



  • 範例1:在這裏,我們將一個字符串轉換為一個 Map,其中鍵作為字符串的單詞,值作為每個單詞的長度。
    
    // 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));
        }
    }
    輸出:
    {Geek=4, for=3, Geeks=5}
    

    在上麵的示例中,toMap Collector將兩個 lambda 函數作為參數:

    1. (價值 -> 價值):它讀取當前流值並將其作為 Map 的鍵返回。
    2. (值-> 值.長度):它讀取當前流值,找到它的長度並將值返回給給定鍵的 Map。
  • 範例2:現在,讓我們使用 toMap 函數執行更複雜的Map轉換。在這裏,我們將用戶列表轉換為一個映射,其中 UserId 是鍵,用戶是值。
    
    // 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));
        }
    }
    輸出:

    {1=User [userId = 1, name = User1, city = Pune], 2=User [userId = 2, name = User2, city = Mumbai], 3=User [userId = 3, name = User3, city = Nagpur]}

方法二:使用Collector

groupingBy Collector將一個函數作為輸入,並使用該函數創建一組流對象。以下是使用 groupingBy Collector將流轉換為Map的示例。

  • 範例1:在本例中,我們將用戶流轉換為Map,其鍵是城市,值是居住在該城市的用戶。
    
    // 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));
        }
    }
    輸出:

    {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]]}

  • 範例2:如果我們需要比實際對象更多的信息,我們還可以為 groupingBy 提供額外的Collector。在此示例中,我們將了解如何獲取屬於每個城市的用戶數。
    
    // 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));
        }
    }
    輸出:
    {Nagpur=1, Pune=2, Mumbai=2}
    




相關用法


注:本文由純淨天空篩選整理自prasadanc1011大神的英文原創作品 How to convert a Stream into a Map in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。