Java8新特性Stream之list转map及问题解决
作者:互联网
List集合转Map,用到的是Stream中Collectors的toMap方法:Collectors.toMap
具体用法实例如下:
//声明一个List集合
List<Person> list = new ArrayList();
list.add(new Person("1001", "小A"));
list.add(new Person("1002", "小B"));
list.add(new Person("1003", "小C"));
System.out.println(list);
//将list转换map
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName));
System.out.println(map);
输出结果为:
解决方法:(分三种,具体哪种看业务需求)
1.重复时用后面的value 覆盖前面的value
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(key1 , key2)-> key2 ));
System.out.println(map);
输出结果:
2.重复时将前面的value 和后面的value拼接起来;
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(key1 , key2)-> key1+","+key2 ));
System.out.println(map);
输出结果:
3.重复时将重复key的数据组成集合
Map<String, List<String>> map = list.stream().collect(Collectors.toMap(Person::getId,
p -> {
List<String> getNameList = new ArrayList<>();
getNameList.add(p.getName());
return getNameList;
},
(List<String> value1, List<String> value2) -> {
value1.addAll(value2);
return value1;
}
));
System.out.println(map);
输出结果:
解决方法:在转换流中加上判空,即便value为空,依旧输出。(与上面方法三相同)
Map<String, List<String>> map = list.stream().collect(Collectors.toMap(Person::getId,
p -> {
List<String> getNameList = new ArrayList<>();
getNameList.add(p.getName());
return getNameList;
},
(List<String> value1, List<String> value2) -> {
value1.addAll(value2);
return value1;
}
))
System.out.println(map);
输出结果为:
标签:map,toMap,Collectors,Stream,List,list,Person 来源: https://blog.csdn.net/segegefe/article/details/123637016