-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainLesson5_2.java
More file actions
62 lines (51 loc) · 1.98 KB
/
MainLesson5_2.java
File metadata and controls
62 lines (51 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package ru.MylearnCh1J1L1;
import java.util.Map;
import java.util.HashMap;
import java.util.LinkedHashMap;
public class MainLesson5_2 {
public static void main(String[] args) {
Map<String, Integer> namesDict = new HashMap<>();
String[] namesArr = {
"Иван Иванов",
"Светлана Петрова",
"Кристина Белова",
"Анна Мусина",
"Анна Крутова",
"Иван Юрин",
"Петр Лыков",
"Павел Чернов",
"Петр Чернышов",
"Мария Федорова",
"Марина Светлова",
"Мария Савина",
"Мария Рыкова",
"Марина Лугова",
"Анна Владимирова",
"Иван Мечников",
"Петр Петин",
"Иван Ежов"
};
for (String el: namesArr) {
String name = el.split(" ")[0];
if (namesDict.containsKey(name)) {
namesDict.replace(name, namesDict.get(name) + 1);
}
else namesDict.put(name, 1);
}
Map<String, Integer> sortedDict = sortHashMap(namesDict);
System.out.println(namesDict);
System.out.println(sortedDict);
}
public static Map<String, Integer> sortHashMap(Map<String, Integer> map) {
Map<String, Integer> sortedMap = new LinkedHashMap<>();
int max = 1;
for (int value: map.values())
if (value > max) max = value;
for (int i = max; i > 0; i--) {
for (var el: map.entrySet())
if (map.get(el.getKey()) == i)
sortedMap.put(el.getKey(), el.getValue());
}
return sortedMap;
}
}