java list 转 map
可以使用Java 8的stream来将List转换为Map,假设List中的元素为Student类的实例,其中id是唯一的键,可以这样实现:
List<Student> studentList = Arrays.asList(
new Student(1, "Tom"),
new Student(2, "Jerry"),
new Student(3, "Alice")
);
Map<Integer, Student> studentMap = studentList.stream()
.collect(Collectors.toMap(Student::getId, Function.identity()));
上述代码中,使用stream()方法将List转换为Stream,然后使用collect()方法将Stream转换为Map。其中toMap()方法接受两个参数,第一个参数指定Map的键,第二个参数指定Map的值,这里使用Function.identity()表示使用原始元素作为值。如果List中存在重复的键,可以使用第三个参数来指定如何处理重复的键。
原文地址: https://www.cveoy.top/t/topic/bIIn 著作权归作者所有。请勿转载和采集!