当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。