提交 22391b5f 编写于 作者: M Mars Liu

add to map

上级 fc7afb4e
无相关合并请求
{
"node_id": "java-e5d307b8ce2049648b4afd9fecdb48b0",
"keywords": []
}
\ No newline at end of file
......@@ -2,5 +2,9 @@
"node_id": "java-0f1fc49b2e1c41368403ca2239810920",
"keywords": [],
"children": [],
"export": ["to_list.json"]
"export": [
"to_list.json",
"to_set.json",
"to_map.json"
]
}
\ No newline at end of file
{
"type": "code_options",
"author": "刘鑫",
"source": "to_map.md",
"notebook_enable": false
}
\ No newline at end of file
# Stream To Map
现有类型 Person 如下:
```java
public class Person{
private final int id;
private final String name;
public Person(int id, String name){
this.id = id;
this.name = name;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
}
```
下面的程序将 `Stream<Person> people` 中的数据整理到一个 Map<Integer, String> 字典中,键和值分别对应 Person 类型的 id 和name。其中有错的是:
## 答案
```java
Map<Integer, String> dict = new Map();
people.collect(p ->{
dict.put(p.getId(), p.getName());
});
```
## 选项
### 常规收集器
```java
Map<Integer, String> dict = people().collect(Collectors.toMap(Person::getId, Person::getName));
```
### 朴素的过程化方法
```java
Map<Integer, String> dict = new HashMap<>();
people.forEach(p->{
dict.put(p.getId(), p.getName());
});
```
### 朴素的 for 循环,不推荐但是能用
```java
Map<Integer, String> dict = new HashMap<>();
for(var p: people.toList()){
dict.put(p.getId(), p.getName());
}
```
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册
反馈
建议
客服 返回
顶部