java 8 stream List 转 map
时间: 2023-09-23 15:03:34 浏览: 48
可以使用Stream的collect方法将List转换为Map。示例如下:
假设有一个Student类,包含id和name属性:
```
public class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
```
现在有一个List<Student>,需要将其转换为Map<Integer, String>,其中key为Student的id,value为Student的name。
可以使用以下代码实现:
```
List<Student> students = Arrays.asList(
new Student(1, "Alice"),
new Student(2, "Bob"),
new Student(3, "Charlie")
);
Map<Integer, String> studentMap = students.stream()
.collect(Collectors.toMap(Student::getId, Student::getName));
System.out.println(studentMap);
```
输出结果为:
```
{1=Alice, 2=Bob, 3=Charlie}
```
这里使用了Stream的collect方法,其中参数为Collectors.toMap方法,该方法接受两个Function作为参数,第一个Function用于提取Map的key,第二个Function用于提取Map的value。在这个例子中,我们使用Student的getId方法作为key,使用Student的getName方法作为value。