ilianrusev

Maps, Lambda and Stream API - Exercise - Student Academy

Mar 19th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.util.*;
  4.  
  5.  
  6. public class Main {
  7.  
  8.     public static void main(String[] args) {
  9.  
  10.         Scanner scanner = new Scanner(System.in);
  11.  
  12.         int n = Integer.parseInt(scanner.nextLine());
  13.         Map<String, List<Double>> students = new LinkedHashMap<>();
  14.         Map<String, Double> finalList = new LinkedHashMap<>();
  15.  
  16.         for (int i = 0; i < n; i++) {
  17.             String name = scanner.nextLine();
  18.             Double grade = Double.parseDouble(scanner.nextLine());
  19.  
  20.             if (!students.containsKey(name)){
  21.                 students.put(name, new ArrayList<>());
  22.                 students.get(name).add(grade);
  23.             }else {
  24.                 students.get(name).add(grade);
  25.             }
  26.  
  27.         }
  28.  
  29.  
  30.  
  31.  
  32.  
  33.  
  34.  
  35.  
  36.  
  37.         students.entrySet()
  38.                 .forEach(e -> {
  39.                             Double average = e.getValue()
  40.                                     .stream()
  41.                                     .mapToDouble(x -> x)
  42.                                     .average()
  43.                                     .getAsDouble();
  44.                             if (average >= 4.50) {
  45.                                 finalList.put(e.getKey(), average);
  46.                             }
  47.                         });
  48.         finalList.entrySet()
  49.                 .stream()
  50.                 .sorted((a,b) -> Double.compare(b.getValue(),
  51.                                     a.getValue()))
  52.                 .forEach(c -> {
  53.                                 System.out.println(String.format("%s -> %.2f", c.getKey(), c.getValue()));
  54.                             });
  55.  
  56.     }
  57. }
Add Comment
Please, Sign In to add comment