Repository navigation
Expand file tree
/
Copy pathTreeMapWorking.java
More file actions
60 lines (48 loc) · 1.53 KB
/
Copy pathTreeMapWorking.java
File metadata and controls
60 lines (48 loc) · 1.53 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 src.collections.maps;
import java.util.Map;
import java.util.TreeMap;
// Standard Comparable
class TreeKey implements Comparable<TreeKey> {
// Custom input
final int data = 118;
private String key;
// Constructor of this class
public TreeKey(String key) {
// Super keyword refers immediate parent class
// object
super();
// This keyword is a reference variable
// referring to current object
this.key = key;
}
// Print Key method
public String printKey() {
return this.key;
}
// Override compareTo method
@Override
public int compareTo(TreeKey obj) {
return key.compareTo(obj.key);
}
}
// Main Class
class TreeMapWorking {
// Main driver method
public static void main(String[] args) {
// Initialize TreeMap
// Declaring object of String type
Map<TreeKey, String> treemap = new TreeMap<>();
// Adding the elements in object of TreeMap
// Custom inputs
treemap.put(new TreeKey("Key1"), "Alice");
treemap.put(new TreeKey("Key4"), "Zeya");
treemap.put(new TreeKey("Key3"), "Geek");
treemap.put(new TreeKey("Key2"), "Bob");
// Iterate over object elements using for-each loop
for (Map.Entry<TreeKey, String> entry : treemap.entrySet())
// Print elements in TreeMap object
System.out.println(
"[" + entry.getKey().printKey() + " = "
+ entry.getValue() + "]");
}
}