java8 lambda List 转换 Map

oyhk 学习笔记

  • 实体类

    1. class User{
    2. private Long id;
    3. private String username;
    4. }
  • 没有使用lambda

    1. private Map<String, User> toMap(List userList) {
    2. Map hashMap = new HashMap<>();
    3. for (User user : userList) {
    4. hashMap.put(user.getId(),user);
    5. }
    6. return hashMap;
    7. }
  • 使用lambda

    1. public void test(){
    2. List<User> userList = new ArrayList<>();
    3. Map<Long,User> userMap = userList.stream().collect(Collectors.toMap(user -> user.getId(), user -> user));
    4. }

确实清爽很多- -