Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package AssociativeArraysExercise;
- import java.util.*;
- import static java.util.stream.Collectors.toMap;
- public class Courses {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- Map<String, ArrayList<String>> courses = new LinkedHashMap<>();
- String input = " ";
- while (!"end".equals(input = scanner.nextLine())) {
- String[] data = input.split(" : ");
- String course = data[0];
- String student = data[1];
- if (!courses.containsKey(course)) {
- courses.put(course, new ArrayList<>());
- courses.get(course).add(student);
- } else {
- courses.get(course).add(student);
- Collections.sort(courses.get(course));
- }
- }
- Map<String, List<String>> sorted = courses.entrySet().stream()
- .sorted((e1,e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size()))
- .collect(toMap(
- Map.Entry::getKey,
- Map.Entry::getValue,
- (a,b) -> {throw new AssertionError();},
- LinkedHashMap::new
- ));
- for (Map.Entry<String,List<String>> course : sorted.entrySet()) {
- System.out.println(String.format("%s: %d",course.getKey(), course.getValue().size()));
- List<String> studentNames = course.getValue();
- for (String name: studentNames) {
- System.out.println(" -- " + name);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement