例如:
public class User {
private Integer id;
private String name;
public User(Integer id, String name) {
this.id = id;
this.name = name;
}
}
把User集合转成key ->id ,value->User对象的map 1.最原始方法
List<User> list = new ArrayList<>();
list.add(new User(1,"a"));
list.add(new User(2,"b"));
HashMap<Integer, User> map = new HashMap<>();
for (User u:list) {
map.put(u.getId(),u);
}
2.stream流式操作
HashMap<Integer, User> map1 = list.stream()
.collect(HashMap::new, (m, v) -> m.put(v.getId(), v), HashMap::putAll);
3.stream流简化操作(推荐)
Map<Integer, User> map2 = list.stream().
collect(Collectors.toMap(User::getId, Function.identity()));
输出结果
第一种:{1=User(id=1, name=a), 2=User(id=2, name=b)}
第二种:{1=User(id=1, name=a), 2=User(id=2, name=b)}
第三种:{1=User(id=1, name=a), 2=User(id=2, name=b)}
|