Several days did not update the article, on the one hand because of work reasons, on the other hand because xiaobian secretly preparing for the interview, due to lack of preparation, in yesterday was ruthless…… Eliminated! Java8 convert a List to a Map, then I summarized the List to Map three methods. The first method is probably a common one that uses a for loop to fill each element into the map, for example:

 ArrayList<User> list=new ArrayList<>();
 Map maps=new HashMap();
 list.add(new User("1"."Zhang"));
 list.add(new User("2"."Bill"));
 list.add(new User("3"."Fifty"));
 for (User users:list){
      maps.put(users.getUserId(),users.getUserName());
  }
 System.out.println(maps);
Copy the code

The second is to use the Guava library of tools provided by Google

 Map<String,User> map = Maps.uniqueIndex( list, user -> user.getUserId());
 System.out.println(map);
Copy the code

The third method, Java8’s Stream method, is the easiest and provides functions that effectively resolve Key conflicts

 System.out.println(list.stream().collect(Collectors.toMap(User::getUserId,User::getUserName,(k1,k2)->k2)));
Copy the code