-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashmapKeysSorting.java
More file actions
60 lines (53 loc) · 2.01 KB
/
Copy pathHashmapKeysSorting.java
File metadata and controls
60 lines (53 loc) · 2.01 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
package interviewprograms.src;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/*
1. HashMap contains entry(key and value).
2. Map<Integer,String> map=new HashMap<>();
3. map.put(102, "Operating System");
4. map.remove(102);
5. Iteration in map:
for (Map.Entry<Integer, String> entry : map.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
}
6. Java TreeMap class implements the Map interface by using a tree.
7. TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
7. hm.put(100,"Amit");
*/
public class HashmapKeysSorting {
public static void main(String[] args) {
Map<String,String> unsortedMap=new HashMap<>(); //Will randomly place string values
unsortedMap.put("Dell", "Dell");
unsortedMap.put("Asus", "Asus");
unsortedMap.put("Samsung", "Samsung");
unsortedMap.put("HP", "HP");
unsortedMap.put("Apple", "Apple");
unsortedMap.put("Lenovo", "Lenovo");
for (Map.Entry<String, String> entry : unsortedMap.entrySet()) {
System.out.println("Unsorted key value: "+ entry.getKey());
}
System.out.println("\n");
Map<String, String> sortedMap= new TreeMap<>(unsortedMap); //This data structure sorts the map.
for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
String key = entry.getKey();
System.out.println("Sorted key values are: "+ entry.getKey());
}
}
}
/*
run:
Unsorted key value: Lenovo
Unsorted key value: Dell
Unsorted key value: Apple
Unsorted key value: HP
Unsorted key value: Samsung
Unsorted key value: Asus
Sorted key values are: Apple
Sorted key values are: Asus
Sorted key values are: Dell
Sorted key values are: HP
Sorted key values are: Lenovo
Sorted key values are: Samsung
*/