我有一个包含主题ArrayList的HashMap。每个学生都有不同的笔记。如何从HashMap打印这些笔记?在我的代码末尾,我有println
,如果我想打印某个主题的特定平均值,我该怎么做?
Student student1 = new Apprentice("Jack", "Morgan");
Subject english = new Subject("English", Arrays.asList(2, 3, 2, 2));
Subject japanese = new Subject("japanese", Arrays.asList(2, 2, 2, 4));
HashMap<Student, List<Subject>> studentGrade = new HashMap<>();
studentGrade.put(student1, Arrays.asList(english, japanese));
for (Map.Entry<Apprentice, List<Subject> > entry : apprenticeGrades.entrySet()) {
System.out.println("Student " + entry.getKey());
for (Subject subject : entry.getValue()) {
System.out.println("Average from subject:" + subject.getAvg());
}
答案 0 :(得分:0)
final List<Subject> subjectList = studentGrade
// get a Collection<List<Subject>>
.values()
// make a stream from the collection
.stream()
// turn each List<Subject> into a Stream<Subject> and merge these streams
.flatMap(List::stream)
// accumulate the result into a List
.collect(Collectors.toList());
for(Subject subject : subjectList){
System.out.println("Average from subject:" + subject.getAvg());
}
首先将所有主题(值)放入列表中并迭代它以计算并打印平均值。