使用Java 8将List
javaList2. 使用Stream API将ListstudentList = new ArrayList<>();studentList.add(new Student("Alice", 18));studentList.add(new Student("Bob", 20));studentList.add(new Student("Charlie", 19));
javaMap在上面的代码中,我们使用`stream()`方法将ListstudentMap = studentList.stream() .collect(Collectors.toMap(Student::getName, Student::getAge));
javaimport 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 studentList = new ArrayList<>(); studentList.add(new Student("Alice", 18)); studentList.add(new Student("Bob", 20)); studentList.add(new Student("Charlie", 19)); Map studentMap = studentList.stream() .collect(Collectors.toMap(Student::getName, Student::getAge)); System.out.println(studentMap); }} 使用Java 8将List