This example covers tree-map example in java:
TreeMap tm = new TreeMap();
// Put elements to the map
tm.put("Kinshuk Chandra", new Double(3434.34));
tm.put("Himanshu Singh", new Double(123.22));
tm.put("Gaurav Mishra", new Double(1378.00));
tm.put("Mohit Mittal", new Double(99.22));
tm.put("Chitranshu Mishra", new Double(-19.08));
// Get a set of the entries
Set set = tm.entrySet();
// Get an iterator
Iterator i = set.iterator();
// Display elements
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into My (Kinshuk Chandra's) account
double balance = ((Double)tm.get("Kinshuk Chandra")).doubleValue();
tm.put("Kinshuk Chandra", new Double(balance + 1000));
System.out.println("Kinshuk Chandra's new balance: " +
tm.get("Kinshuk Chandra"));
Output:
Chitranshu Mishra: -19.08
Gaurav Mishra: 1378.0
Himanshu Singh: 123.22
Kinshuk Chandra: 3434.34
Mohit Mittal: 99.22
Kinshuk Chandra's current balance: 4434.34
Notice that TreeMap sorts the keys. However, in this case, they are sorted by first name instead of last name. You can alter this behavior by specifying a comparator when the map is created.
No comments:
Post a Comment