Java Stream: 使用 collect 和 toMap 将 List 转为 Map
要使用流(Stream)将List转为Map,可以使用Stream的collect方法,结合Collectors的toMap方法来实现。
假设有一个List
示例代码如下:
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Student> students = List.of(
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);
}
}
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;
}
}
运行以上代码,将会输出以下结果:
{1=Alice, 2=Bob, 3=Charlie}
通过stream的collect方法,配合Collectors的toMap方法,可以将List转为Map。在toMap方法中,第一个参数指定了Map的键,第二个参数指定了Map的值。
在示例代码中,我们使用Student的id作为键,name作为值,将List
原文地址: https://www.cveoy.top/t/topic/qlSh 著作权归作者所有。请勿转载和采集!