desislava_topuzakova

09. User Logs

May 31st, 2021
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class UserLogs_09 {
  4. public static void main(String[] args) {
  5. Scanner scanner = new Scanner(System.in);
  6. String input = scanner.nextLine();
  7. TreeMap<String, LinkedHashMap<String, Integer>> info = new TreeMap<>();
  8. while (!input.equals("end")) {
  9. //"IP={ip} message={message} user={username}"
  10. String[] data = input.split("\\s+"); //["IP={ip}", "message={message}", "user={username}"]
  11. String username = data[2].split("=")[1]; //"user={username}".split("=") -> ["user", "{username}"]
  12. //String message = data[1].split("=")[1]; //"message={message}".split("=") -> ["message", "{message}"]
  13. String ip = data[0].split("=")[1]; //"IP={ip}".split("=") => ["IP", "{ip}"]
  14.  
  15. //info.putIfAbsent(username, new LinkedHashMap<>()); //добавя запис ако го няма ключ if(info.containsKey(username))
  16. //info.get(username).putIfAbsent(ip, 0); //добавя запис ако го няма
  17. //info.get(username).put(ip, info.get(username).get(ip) + 1);
  18.  
  19. //1. проверка има ли username
  20. if (info.containsKey(username)) {
  21. LinkedHashMap<String, Integer> ips = info.get(username); //ip -> count
  22. if (ips.containsKey(ip)) {
  23. ips.put(ip, ips.get(ip) + 1);
  24. } else {
  25. ips.put(ip, 1);
  26. }
  27.  
  28. } else {
  29. info.put(username, new LinkedHashMap<>());
  30. info.get(username).put(ip, 1);
  31. }
  32.  
  33. input = scanner.nextLine();
  34. }
  35.  
  36. info.entrySet().stream().
  37. forEach(entry -> { //username -> map
  38. System.out.println(entry.getKey() + ":");
  39. for (var ipEntry : entry.getValue().entrySet()) {
  40. //ip -> count
  41. //IP => count,
  42. System.out.println(ipEntry.getKey() + " => " + ipEntry.getValue() + ", ");
  43. //TODO: LAST ENTRY TO BE PRINTED WITH . IN THE END
  44. }
  45. }
  46. );
  47. }
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment