用Java8把List转为Map

 1 import com.yang.test.User;
 2  
 3 import javax.jws.soap.SOAPBinding;
 4 import java.util.*;
 5 import java.util.function.Function;
 6 import java.util.stream.Collectors;
 7  
 8 public class Main {
 9  
10     public static void main(String[] args) {
11  
12         List<User> userlist = new ArrayList<>();
13         for (int i = 0; i <10; i++) {
14  
15             userlist.add(new User("张三"+i,i));
16         }
17         System.out.println(getAllages(userlist).size());
18  
19         System.out.println(getUser2Map(userlist));
20  
21         System.out.println(getUser2MapUser(userlist));
22  
23         System.out.println(getUser2MapUser2(userlist));
24  
25           System.out.println(getUser2MapUser3(userlist));
26  
27     }
28  
29     public static List<Integer> getAllages(List<User>userlist){
30         return  userlist.stream().map(user -> user.getAge()).collect(Collectors.toList());
31     }
32  
33     public static Map<Integer,String> getUser2Map(List<User>userlist){
34  
35         return userlist.stream().collect(Collectors.toMap(User::getAge,User::getName));
36     }
37  
38     public static Map<Integer,User> getUser2MapUser(List<User>userlist){
39  
40         return userlist.stream().collect(Collectors.toMap(User::getAge,User-> User));
41     }
42  
43     /**
44      * 比较优雅的写法是这样的
45      * @param userlist
46      * @return
47      */
48     public static Map<Integer,User> getUser2MapUser2(List<User>userlist){
49  
50         return userlist.stream().collect(Collectors.toMap(User::getAge, Function.identity()));
51     }
52  
53     /**
54      * 重复key的情况下 简单的使用后者覆盖前者的
55      */
56     public static Map<Integer,User> getUser2MapUser3(List<User>userlist){
57  
58         return userlist.stream().collect(Collectors.toMap(User::getAge, Function.identity(),(key1,key2)->key2));
59     }
60  
61     /**
62      *指定map的具体实现
63      * @param userlist
64      * @return
65      */
66     public static Map<Integer,User> getUser2MapUser4(List<User>userlist){
67  
68         return userlist.stream().collect(Collectors.toMap(User::getAge, Function.identity(),(key1,key2)->key2, LinkedHashMap::new));
69     }
70 }

 

posted @ 2018-11-17 09:50  `初一`  阅读(8065)  评论(0编辑  收藏  举报