美文网首页Java
Java List to Map && Map to List

Java List to Map && Map to List

作者: 西安法律咨询服务平台与程序员 | 来源:发表于2020-04-28 18:58 被阅读0次

    1 List to Map

    @Getter
    @Setter
    public class User {
        private Long id;
        private String name;
    
        public User(Long id, String name) {
            this.id = id;
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    
    package com.mervyn.filterdemo;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class Test {
        public static void main(String[] args) {
            List<User> names = new ArrayList<>();
            names.add(new User(1L,"郭雨桐"));
            names.add(new User(2L,"尚书雨"));
            names.add(new User(3L,"李雪晴"));
            names.add(new User(4L,"刘小晓"));
            Map<Long, User> userMap = names.stream().collect(Collectors.toMap(User::getId, user -> user));
        }
    }
    

    2 Map to List

    package com.mervyn.filterdemo;
    
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class Test {
        public static void main(String[] args) {
            Map<Long, String> userMap = new HashMap<>();
            userMap.put(1L, "郭雨桐");
            userMap.put(2L, "尚书雨");
            userMap.put(3L, "李雪晴");
            userMap.put(4L, "刘小晓");
            // 将Map的value值转成list
            List<String> usernames = userMap.values().stream().collect(Collectors.toList());
            // 将Map的key值转成list
            List<Long> userIds = userMap.keySet().stream().collect(Collectors.toList());
        }
    }
    

    相关文章

      网友评论

        本文标题:Java List to Map && Map to List

        本文链接:https://www.haomeiwen.com/subject/dreywhtx.html