atanasovetr

Mira

Aug 14th, 2021
1,240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.14 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.stream.Collectors;
  3.  
  4. public class exercise1 {
  5.     public static void main(String args[]) {
  6.         Scanner scan = new Scanner(System.in);
  7.         String command = scan.nextLine();
  8.         HashMap<String, Integer> users = new HashMap<>();
  9.         String username;
  10.  
  11.  
  12.         while (!command.equals("Log out")) {
  13.             username = command.split(": ")[1];
  14.             if (command.contains("New follower: ")) {
  15.                 if (!users.containsKey(username)) {
  16.                     users.put(username, 0);
  17.                 }
  18.             } else if (command.contains("Like: ")) {
  19.                 int likes = Integer.parseInt(command.split(": ")[2]);
  20.                 if (!users.containsKey(username)) {
  21.                     users.put(username, likes);
  22.                 } else {
  23.                     users.put(username, users.get(username) + likes);
  24.                 }
  25.             } else if (command.contains("Comment: ")) {
  26.                 if (!users.containsKey(username)) {
  27.                     users.put(username, 1);
  28.                 } else {
  29.                     users.put(username, users.get(username) + 1);
  30.                 }
  31.             } else if (command.contains("Blocked: ")) {
  32.                 if (!users.containsKey(username)) {
  33.                     System.out.println(String.format("%s doesn't exist.", username));
  34.                 } else {
  35.                     users.remove(username);
  36.                 }
  37.             }
  38.  
  39.             command = scan.nextLine();
  40.         }
  41.  
  42.         HashMap<String, Integer> sortedUsers = users.entrySet()
  43.                 .stream()
  44.                 .sorted(Collections.reverseOrder(Map.Entry.<String, Integer>comparingByValue())
  45.                         .thenComparing(Map.Entry.comparingByKey()))
  46.                 .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
  47.                         (newValue, oldValue) -> oldValue, LinkedHashMap::new));
  48.  
  49.         System.out.println(String.format("%d followers", sortedUsers.size()));
  50.         sortedUsers.entrySet().forEach(entry -> {
  51.             System.out.println(entry.getKey() + ": " + entry.getValue());
  52.         });
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment