有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

作为HashMap值的java打印数组列表

我有一个包含主题列表的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());
    }

共 (1) 个答案

  1. # 1 楼答案

     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());
            }
    

    首先将所有主题(值)放在一个列表中,然后迭代计算并打印平均值