Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class Test {
- public static void main(String[] args) {
- String text = "Егор мыло 3 Алла сок 3 Марианна печенье " +
- "7 Кирилл пиво 2 Егор шампунь 1 Алла пиво 1 Егор мыло 1";
- TextSeparator textSeparator = new TextSeparator(text);
- textSeparator.showSortedText();
- }
- }
- class TextSeparator {
- private Map<String, TreeMap<String, Integer>> hashMap = new HashMap<>();
- private String[] namesStuffAndCount;
- TextSeparator(String string) {
- namesStuffAndCount = string.split(" ");
- }
- private void sortText() {
- String name;
- String stuff;
- int count;
- for (int i = 0; i < namesStuffAndCount.length; i += 3) {
- name = namesStuffAndCount[i];
- stuff = namesStuffAndCount[i + 1];
- count = Integer.parseInt(namesStuffAndCount[i + 2]);
- if (!hashMap.containsKey(name)) {
- hashMap.put(name, new TreeMap<>());
- }
- TreeMap<String, Integer> temp = hashMap.get(name);
- if (!temp.containsKey(stuff)) {
- temp.put(stuff, count);
- } else {
- temp.put(stuff, temp.get(stuff) + count);
- }
- }
- }
- public void showSortedText() {
- sortText();
- String temp;
- for (Map.Entry entry : hashMap.entrySet()) {
- temp = (String) entry.getKey();
- System.out.println(temp + ": ");
- TreeMap<String, Integer> temp1 = hashMap.get(entry.getKey());
- for (Map.Entry entry1 : temp1.entrySet()) {
- System.out.println(" " + entry1.getKey() + " " + entry1.getValue());
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement