Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2022
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.81 KB | None | 0 0
  1. package Exams;
  2.  
  3. import java.util.*;
  4.  
  5. public class SnowwhiteFromMoreExercise {
  6.  
  7.     public static void main(String[] args) {
  8.         Scanner scanner = new Scanner(System.in);
  9.  
  10.         Map<String, Map<String, Dwarf>> dwarfsByColor = new LinkedHashMap<>();
  11.  
  12.         String input = "";
  13.         while (!"Once upon a time".equals(input = scanner.nextLine())) {
  14.  
  15.             String[] arr = input.split(" <:> ");
  16.  
  17.             String name = arr[0];
  18.             String color = arr[1];
  19.             int physics = Integer.parseInt(arr[2]);
  20.  
  21.             dwarfsByColor.putIfAbsent(color, new LinkedHashMap<>());
  22.             dwarfsByColor.get(color)
  23.                     .merge(name, new Dwarf(name, color, physics),
  24.                             (oldD, newD) -> (oldD.physics >= newD.physics) ? oldD : newD);
  25.         }
  26.  
  27.         final Comparator<Dwarf> dwarfComparator = (dwarf1, dwarf2) -> {
  28.             int sort = Integer.compare(dwarf2.physics, dwarf1.physics);
  29.             if (sort == 0) {
  30.                 sort = Integer.compare(dwarfsByColor.get(dwarf2.hatColor).size(),
  31.                         dwarfsByColor.get(dwarf1.hatColor).size());
  32.             }
  33.             return sort;
  34.         };
  35.  
  36.         dwarfsByColor.values().stream()
  37.                 .map(Map::values)
  38.                 .flatMap(Collection::stream)
  39.                 .sorted(dwarfComparator)
  40.                 .forEach(dwarf -> System.out.printf("(%s) %s <-> %d%n", dwarf.hatColor, dwarf.name, dwarf.physics));
  41.     }
  42.  
  43.     private static final class Dwarf {
  44.         private final String name;
  45.         private final String hatColor;
  46.         private final int physics;
  47.  
  48.         public Dwarf(String name, String hatColor, int physics) {
  49.             this.name = name;
  50.             this.hatColor = hatColor;
  51.             this.physics = physics;
  52.         }
  53.     }
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement