Advertisement
Guest User

Untitled

a guest
Apr 4th, 2020
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.85 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class Test {
  4.     public static void main(String[] args) {
  5.  
  6.         String text = "Егор мыло 3 Алла сок 3 Марианна печенье " +
  7.                 "7 Кирилл пиво 2 Егор шампунь 1 Алла пиво 1 Егор мыло 1";
  8.         TextSeparator textSeparator = new TextSeparator(text);
  9.         textSeparator.showSortedText();
  10.     }
  11. }
  12.  
  13. class TextSeparator {
  14.  
  15.     private Map<String, TreeMap<String, Integer>> hashMap = new HashMap<>();
  16.     private String[] namesStuffAndCount;
  17.  
  18.     TextSeparator(String string) {
  19.         namesStuffAndCount = string.split(" ");
  20.     }
  21.  
  22.     private void sortText() {
  23.  
  24.         String name;
  25.         String stuff;
  26.         int count;
  27.         for (int i = 0; i < namesStuffAndCount.length; i += 3) {
  28.  
  29.             name = namesStuffAndCount[i];
  30.             stuff = namesStuffAndCount[i + 1];
  31.             count = Integer.parseInt(namesStuffAndCount[i + 2]);
  32.  
  33.             if (!hashMap.containsKey(name)) {
  34.                 hashMap.put(name, new TreeMap<>());
  35.             }
  36.            
  37.             TreeMap<String, Integer> temp = hashMap.get(name);
  38.            
  39.             if (!temp.containsKey(stuff)) {
  40.                 temp.put(stuff, count);
  41.             } else {
  42.                 temp.put(stuff, temp.get(stuff) + count);
  43.             }
  44.         }
  45.     }
  46.  
  47.     public void showSortedText() {
  48.        
  49.         sortText();
  50.         String temp;
  51.        
  52.         for (Map.Entry entry : hashMap.entrySet()) {
  53.             temp = (String) entry.getKey();
  54.             System.out.println(temp + ": ");
  55.             TreeMap<String, Integer> temp1 = hashMap.get(entry.getKey());
  56.            
  57.             for (Map.Entry entry1 : temp1.entrySet()) {
  58.                 System.out.println(" " + entry1.getKey() + " " + entry1.getValue());
  59.             }
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement