Mega Code Archive

 
Categories / Java Book / 005 Collection
 

0316 TreeMap Class

The TreeMap class extends AbstractMap and implements the NavigableMap interface. It creates maps stored in a tree structure. A tree map guarantees that its elements will be sorted in an order. TreeMap is a generic class that has this declaration: class TreeMap<K, V> K specifies the type of keys V specifies the type of values. The following TreeMap constructors are defined: TreeMap( ) constructs an empty tree map that will be sorted by using the natural order of its keys. TreeMap(Comparator<? super K> comp) constructs an empty tree-based map that will be sorted by using the Comparator comp. TreeMap(Map<? extends K, ? extends V> m) initializes a tree map with the entries from m, which will be sorted by using the natural order of the keys. TreeMap(SortedMap<K, ? extends V> sm) initializes a tree map with the entries from sm, which will be sorted in the same order as sm. TreeMap has no methods beyond those specified by the NavigableMap interface and the AbstractMap class. The following code sorts a map's entries according to the natural ordering of their String-based keys import java.util.Map; import java.util.TreeMap; public class Main { public static void main(String[] args) { Map<String, Integer> msi = new TreeMap<String, Integer>(); String[] fruits = { "apples", "pears", "grapes", "bananas", "kiwis" }; int[] quantities = { 10, 15, 8, 17, 30 }; for (int i = 0; i < fruits.length; i++){ msi.put(fruits[i], quantities[i]); } for (Map.Entry<String, Integer> entry : msi.entrySet()){ System.out.println(entry.getKey() + ": " + entry.getValue()); } } } apples: 10 bananas: 17 grapes: 8 kiwis: 30 pears: 15 The following program uses TreeMap: import java.util.Map; import java.util.Set; import java.util.TreeMap; public class Main { public static void main(String args[]) { TreeMap<String, Double> tm = new TreeMap<String, Double>(); tm.put("J", new Double(3.34)); tm.put("T", new Double(1.22)); tm.put("J", new Double(1.00)); tm.put("T", new Double(9.22)); tm.put("R", new Double(-1.08)); Set<Map.Entry<String, Double>> set = tm.entrySet(); for (Map.Entry<String, Double> me : set) { System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } double balance = tm.get("J"); tm.put("J", balance + 1000); System.out.println(tm.get("J")); } }