Advertisement
shniaga

Untitled

Mar 18th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. package AssociativeArraysExercise;
  2.  
  3. import java.util.*;
  4.  
  5. import static java.util.stream.Collectors.toMap;
  6.  
  7. public class Courses {
  8. public static void main(String[] args) {
  9. Scanner scanner = new Scanner(System.in);
  10.  
  11. Map<String, ArrayList<String>> courses = new LinkedHashMap<>();
  12.  
  13. String input = " ";
  14.  
  15. while (!"end".equals(input = scanner.nextLine())) {
  16.  
  17. String[] data = input.split(" : ");
  18. String course = data[0];
  19. String student = data[1];
  20.  
  21. if (!courses.containsKey(course)) {
  22. courses.put(course, new ArrayList<>());
  23. courses.get(course).add(student);
  24. } else {
  25. courses.get(course).add(student);
  26. Collections.sort(courses.get(course));
  27. }
  28. }
  29.  
  30. Map<String, List<String>> sorted = courses.entrySet().stream()
  31. .sorted((e1,e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size()))
  32. .collect(toMap(
  33. Map.Entry::getKey,
  34. Map.Entry::getValue,
  35. (a,b) -> {throw new AssertionError();},
  36. LinkedHashMap::new
  37. ));
  38.  
  39. for (Map.Entry<String,List<String>> course : sorted.entrySet()) {
  40. System.out.println(String.format("%s: %d",course.getKey(), course.getValue().size()));
  41.  
  42. List<String> studentNames = course.getValue();
  43. for (String name: studentNames) {
  44. System.out.println(" -- " + name);
  45. }
  46. }
  47.  
  48.  
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement