import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
Student student = new Student();
StudentDB studentDb = new StudentDB();
System.out.println("All Elements from the List \n");
studentDb.getStudentList().forEach(System.out::println);
Map<String, List<String>> studentMap = studentDb.getStudentList().stream()
.collect(Collectors.toMap(student.getName(), student.getActivities()));
}
}
使用的是东西,student.getName()
它只是在对象上调用方法,因此您将获得其名称和活动,将获得值,没有通用方法来终止Stream
该Collectors.toMap
希望你传递函数(Function<Student,String>
关键,Function<Student,List<String>>
对于价值),即从Student
会给别的东西
您可以使用lambda表示它: s -> s.getName()
Map<String, List<String>> studentMap = studentDb.getStudentList().stream()
.collect(Collectors.toMap(s -> s.getName(), s -> s.getActivities()));
或方法参考Student::getName
,您可以使用方法本身,而不是应用于特定对象
Map<String, List<String>> studentMap = studentDb.getStudentList().stream()
.collect(Collectors.toMap(Student::getName, Student::getActivities));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句