Advertisement
RGAlex

O4. Snow White / Maps, Lambda and Stream API - More Exercise

Mar 27th, 2021
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. package MapsLambdaStreamAPI.MoreExercises;
  2.  
  3. import java.util.*;
  4.  
  5. public class O4SnowWhite {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.         Map<String, Integer> dwarfsInfo = new LinkedHashMap<>();
  9.         String input;
  10.  
  11.         while (!"Once upon a time".equals(input = scanner.nextLine())) {
  12.             String[] command = input.split(" <:> ");
  13.             String nameAndColor = String.format("(%s) %s <->", command[1], command[0]);
  14.             int physics = Integer.parseInt(command[2]);
  15.             dwarfsInfo.putIfAbsent(nameAndColor, 0);
  16.             if (dwarfsInfo.get(nameAndColor) < physics) {
  17.                 dwarfsInfo.put(nameAndColor, physics);
  18.             }
  19.         }
  20.         Map<String, Integer> countColors = new HashMap<>();
  21.         dwarfsInfo.forEach((key, value) -> {
  22.             String[] color = key.split(" ");
  23.             countColors.put(color[0], !countColors.containsKey(color[0]) ? 1 : countColors.get(color[0]) + 1);
  24.         });
  25.         dwarfsInfo.entrySet().stream().
  26.                 sorted((a, b) -> {
  27.                     int sort = b.getValue().compareTo(a.getValue());
  28.                     if (sort == 0) {
  29.                         String[] colorOfA = a.getKey().split(" ");
  30.                         String[] colorOfB = b.getKey().split(" ");
  31.                         sort = countColors.get(colorOfB[0]).compareTo(countColors.get(colorOfA[0]));
  32.                     }
  33.                     return sort;
  34.                 })
  35.                 .forEach(e -> System.out.printf("%s %d%n", e.getKey(), e.getValue()));
  36.     }
  37. }
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement