list转map 空指针
时间: 2023-09-02 18:15:26 浏览: 96
空指针
将List转换为Map时,可能会出现空指针异常的问题。这是因为当List中存在空值时,在使用Collectors的toMap方法时,可能会导致NullPointerException。为了解决这个问题,可以在转换流中添加判空的逻辑,即使value为空,也可以正常输出。可以使用以下代码来实现:
List<Person> list = new ArrayList<>();
list.add(new Person("1001", "小A"));
list.add(new Person("1002", "小B"));
list.add(new Person("1003", "小C"));
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName));
System.out.println(map);
若List中存在空值,可以使用以下代码来解决:
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);
以上代码可以将List转换为Map,并解决了空指针异常的问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [List转Map出现的空指针问题](https://blog.csdn.net/m0_59252007/article/details/122409653)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [Java8新特性Stream之list转map及问题解决](https://blog.csdn.net/qq_39629277/article/details/83012548)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文