- Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathHashes.java
More file actions
Latest commit
72 lines (63 loc) · 2.36 KB
/
Copy pathHashes.java
File metadata and controls
72 lines (63 loc) · 2.36 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
63
64
65
66
67
68
69
70
71
72
// Java program to illustrate
// Java.util.HashMap
importjava.util.*;
publicclassHashes {
publicstaticvoidmain(String[] args) {
HashMap<String, Integer> map = newHashMap<>();
System.out.println(map);
map.put("First", 10);
map.put("Second", 30);
map.put("Third", 20);
System.out.println("Size of map is:- " + map.size());
System.out.println(map);
if (map.containsKey("vishal")) {
Integera = map.get("vishal");
System.out.println("value for key" + " \"vishal\" is:- " + a);
}
sortByKey(map);
sortByValue(map);
map.clear();
System.out.println(map);
}
publicstaticvoidprint(Map<String, Integer> map) {
if (map.isEmpty()) {
System.out.println("map is empty");
} else {
System.out.println(map);
}
}
publicstaticvoidsortByKey(Map<String, Integer> map) {
// TreeMap to store values of HashMap
TreeMap<String, Integer> sorted = newTreeMap<>();
// Copy all data from hashMap into TreeMap
sorted.putAll(map);
System.out.println("After sorting by key");
// Display the TreeMap which is naturally sorted
for (Map.Entry<String, Integer> entry : sorted.entrySet())
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
publicstaticvoidsortByValue(HashMap<String, Integer> map) {
List<String> mapKeys = newArrayList<>(map.keySet());
List<Integer> mapValues = newArrayList<>(map.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);
LinkedHashMap<String, Integer> sortedMap = newLinkedHashMap<>();
Iterator<Integer> valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
Integerval = valueIt.next();
Iterator<String> keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
Stringkey = keyIt.next();
Integercomp1 = map.get(key);
Integercomp2 = val;
if (comp1.equals(comp2)) {
keyIt.remove();
sortedMap.put(key, val);
break;
}
}
}
System.out.println("Map Sorted By Value");
System.out.println(sortedMap);
}
}