Didart

Courses - Associative Arrays

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