RGAlex

O6. Courses / Maps, Lambda and Stream API - Exercise

Mar 11th, 2021
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. package MapsLambdaStreamAPI.Exercise;
  2.  
  3. import java.util.*;
  4.  
  5. public class O6Courses {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.         Map<String, List<String>> courses = new LinkedHashMap<>();
  9.         String input = scanner.nextLine();
  10.         while (!input.equals("end")) {
  11.             String course = input.split(" : ")[0];
  12.             String studentName = input.split(" : ")[1];
  13.             if (!courses.containsKey(course)) {
  14.                 courses.put(course, new ArrayList<>());
  15.             }
  16.             courses.get(course).add(studentName);
  17.  
  18.             input = scanner.nextLine();
  19.         }
  20.         courses.entrySet().stream()
  21.                 .sorted((e1, e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size()))
  22.                 .forEach(e -> {
  23.                     System.out.println(e.getKey() + ": " + e.getValue().size());
  24.                     e.getValue().stream()
  25.                             .sorted(String::compareTo)
  26.                             .forEach(student -> System.out.println("-- " + student));
  27.                 });
  28.     }
  29. }
  30.  
Advertisement
Add Comment
Please, Sign In to add comment