
Java
使用Java 8将List
JavaList<Student> studentList = new ArrayList<>();studentList.add(new Student("Alice", 18));studentList.add(new Student("Bob", 20));studentList.add(new Student("Charlie", 19));2. 使用Stream API将Listcollect()方法将Listcollect()方法接受一个Collector参数,我们可以使用Collectors.toMap()方法来创建一个Collector,实现将ListJavaMap<String, Integer> studentMap = studentList.stream() .collect(Collectors.toMap(Student::getName, Student::getAge));在上面的代码中,我们使用
stream()方法将Listcollect()方法和Collectors.toMap()方法将StreamtoMap()方法中,我们将学生姓名作为键(K),学生年龄作为值(V)。注意,我们使用了方法引用(Student::getName和Student::getAge)来指定要提取的键和值。3. 完整的案例代码下面是一个完整的案例代码,演示了如何使用Java 8将ListJavaimport Java.util.ArrayList;import Java.util.List;import Java.util.Map;import Java.util.stream.Collectors;class Student { private String name; private int age; public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; }}public class ListToMapExample { public static void mAIn(String[] args) { List<Student> studentList = new ArrayList<>(); studentList.add(new Student("Alice", 18)); studentList.add(new Student("Bob", 20)); studentList.add(new Student("Charlie", 19)); Map<String, Integer> studentMap = studentList.stream() .collect(Collectors.toMap(Student::getName, Student::getAge)); System.out.println(studentMap); }}使用Java 8将ListCopyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号