Advertisement
IrinaIgnatova

Average Students Grades - TreeMap<String, List<Double>>

Oct 23rd, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.71 KB | None | 0 0
  1. package com.company;
  2.  
  3.  
  4. import java.io.IOException;
  5.  
  6.  
  7. import java.time.LocalTime;
  8. import java.time.format.DateTimeFormatter;
  9. import java.util.*;
  10. import java.util.stream.Collectors;
  11.  
  12. public class Main {
  13.  
  14.  
  15.     public static void main(String[] args) {
  16.         Scanner scanner = new Scanner(System.in);
  17.  
  18.  
  19.         int n = Integer.parseInt(scanner.nextLine());
  20.  
  21.         TreeMap<String, List<Double>> studentWithGrades = new TreeMap<>();
  22.  
  23.  
  24.         for (int i = 0; i < n; i++) {
  25.             String[] input = scanner.nextLine().split(" ");
  26.             String name = input[0];
  27.             double grade = Double.parseDouble(input[1]);
  28.  
  29.  
  30.             if (!studentWithGrades.containsKey(name)) {
  31.                 studentWithGrades.put(name, new ArrayList<>());
  32.                 studentWithGrades.get(name).add(grade);
  33.             } else {
  34.                 studentWithGrades.get(name).add(grade);
  35.  
  36.             }
  37.  
  38.         }
  39.  
  40.         for (Map.Entry<String, List<Double>> entry : studentWithGrades.entrySet()) {
  41.             String studentName = entry.getKey();
  42.             List<Double> grades = entry.getValue();
  43.             double average = grades.stream().mapToDouble(Double::doubleValue).average().getAsDouble();
  44.  
  45. //            String gradesAsString = "";
  46. //            for (int i = 0; i < grades.size(); i++) {
  47. //
  48. //                gradesAsString += grades.get(i) + " ";
  49. //            }
  50.             //System.out.print(gradesAsString);
  51.  
  52.             System.out.printf("%s -> ", studentName);
  53.  
  54.             for (Double grade : grades) {
  55.                 System.out.print(String.format("%.2f ", grade));
  56.             }
  57.  
  58.  
  59.             System.out.printf("(avg: %.2f)%n", average);
  60.         }
  61.  
  62.  
  63.     }
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement