Map<Long, User> maps = new HashMap<>();
for (User user : userList) {
maps.put(user.getId(), user);
}
Map<Long, User> maps = Maps.uniqueIndex(userList, new Function<User, Long>() {
@Override
public Long apply(User user) {
return user.getId();
}
});
使用Java8新特性Stream的Collectors类
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId,Function.identity()));
Map<String, ParamCalcrate> paramCalcrateMap = paramCalcrates.stream().collect(Collectors.toMap(paramCalcrate -> paramCalcrate.getTpId(), Function.identity()));
Map<Integer, String> genderNameMap = pigs.stream()
.collect(
Collectors.toMap(
Pig::getId,
pig -> pig.getName() == null ? "" : pig.getName(),
(oldValue, newValue) -> newValue)
);
genderNameMap.forEach((k, v) -> {
System.out.println(k + " -> " + v.toString());
});
a、key重复
重复时用后面的value 覆盖前面的value
重复时将前面的value 和后面的value拼接起来
重复时将重复key的数据组成集合
2. List 转 Map
Map<String, Long> groupByGenderThenCount = pigs.stream()
.collect(
Collectors.groupingBy(
Pig::getGender,
Collectors.counting()
)
);
groupByGenderThenCount.forEach((k, v) -> {
System.out.println(k + " -> " + v);
});
转换成map的时候,可能出现key一样的情况,如果不指定一个覆盖规则,上面的代码是会报错的。转成map的时候,最好使用下面的方式:
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2));
重复时将前面的value 和后面的value拼接起来
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(key1 , key2)-> key1+","+key2 ));
map的值不是对象,而是对象的某个属性
Map<Long, String> maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2));
List 以ID分组 Map<Integer,List>
Map<Integer, List> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
//List根据某个字段分组
Map<String,List<Student>> sexGroupMap = listStu.stream()
.collect(Collectors.groupingBy(Student::getSex));
Map<String, List<UserPortrait>> map = portraitList.stream().collect(
Collectors.groupingBy(
UserPortrait -> UserPortrait.getPhone() + UserPortrait.getOrganizationId()
));
参考
参考1
参考2
参考3