What is tree map sort?
The TreeMap class implements the Map interface by using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. You should note that, unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order.
Here is an example that will display the treemap elements in a sorted way:
import java.util.*;
public class TreeMapExample {
public static void main(String args[]) {
String days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
int no[] = { 1, 2, 3, 4, 5, 6, 7 };
TreeMap<String,Integer> map = new TreeMap<String,Integer>();
for (int i = 0, n = days.length; i < n; i++) {
map.put(days[i], new Integer(no[i]));
}
Iterator it = map.keySet().iterator();
Object obj;
while (it.hasNext()) {
obj = it.next();
System.out.println(obj + ": " + map.get(obj));
}
}
}
The TreeMap class implements the Map interface by using a tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval. You should note that, unlike a hash map, a tree map guarantees that its elements will be sorted in ascending key order.
Here is an example that will display the treemap elements in a sorted way:
import java.util.*;
public class TreeMapExample {
public static void main(String args[]) {
String days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
int no[] = { 1, 2, 3, 4, 5, 6, 7 };
TreeMap<String,Integer> map = new TreeMap<String,Integer>();
for (int i = 0, n = days.length; i < n; i++) {
map.put(days[i], new Integer(no[i]));
}
Iterator it = map.keySet().iterator();
Object obj;
while (it.hasNext()) {
obj = it.next();
System.out.println(obj + ": " + map.get(obj));
}
}
}