Article From:https://www.cnblogs.com/chuyi-/p/9972931.html
 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("Zhang San "+"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      * The more elegant way of writing is like this.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      * Simply use the latter to override the former when repeating the key55      */
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      *Specific Implementation of Specified Map63      * @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 }

 

Link of this Article: Converting List to Map with Java 8

Leave a Reply

Your email address will not be published. Required fields are marked *