-1

I have a HashMap that contains ArrayList of subjects. Every student has different notes. How can I print those notes from the HashMap? At the end of my code I have println, if I want to print every average specific to a subject, how can I do that?

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());
    }
Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
  • Related: [Difference between Arrays.asList(...) vs new ArrayList<...>(Arrays.asList(...))](https://stackoverflow.com/questions/16748030/difference-between-arrays-aslistarray-vs-new-arraylistintegerarrays-aslist) – Jonny Henly Nov 15 '17 at 18:32
  • 2
    What's the problem? Your code appears to do what you want it to. Are you receiving incorrect output or errors? If so, please [edit] your question to include a proper [mcve]. – Jonny Henly Nov 15 '17 at 18:34

1 Answers1

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

Put all the subjects (values) in a list first and iterate through it to calculate and print the average.

melanzane
  • 483
  • 1
  • 6
  • 16