Tuesday, 2 July 2013

TreeMap in JAVA

TreeMap implements the NavigableMap interface and extends the Abstractmap class.
It contains unique elements.
TreeMap contains the value based on the key. It stores values as key value pairs.
It cannot supports null as key but can have null values.
It maintains ascending order.

Following is the hierarchy of hashMap

 Map

  | extends
  |

SortedMap

  | extends
  |

NavigableMap

  | implements
  |

TreeMap

Example:

/**
 * if key is same and content is same for three values then it will
 * print last value like shown below TreeMap may supports null values
 * but key must be not null(using KeySet Method)
 */
Map map1 = new TreeMap();
map1.put("one", "krishna");
map1.put("one", "krishna1");
map1.put("two", "munna");
map1.put("three", "balu");
// map1.put(null, "anusha");
map1.put("four", "tiger");
Set set1 = map1.keySet();
Iterator iterator1 = set1.iterator();
while (iterator1.hasNext()) {
String object = (String) iterator1.next();
System.out.println(map1.get(object));

}

//==============================================

/**
 * if key is same and content is same for three values then it will
 * print last value like shown below TreeMap may supports null values
 * but key must be not null(Using EntrySet Method)
 */
Map map11 = new TreeMap();
map11.put("one", "krishna");
map11.put("one", "krishna1");
map11.put("two", "munna");
map11.put("three", "balu");
map11.put("four", "tiger");
Set set11 = map11.entrySet();
Iterator iterator11 = set11.iterator();
while (iterator11.hasNext()) {
Map.Entry object = (Map.Entry) iterator11.next();
System.out.println(object.getKey() + "}}}}}}}}}}}}}}}"
+ object.getValue());

}

// ==============================================
/**
 * if key is same and content is same for three values then it will
 * print last value like shown below TreeMap may supports null values
 * but key must be not null(Using EntrySet Method). Tree Map supports
 * different types of objects like strings,integers but key must be same
 * other wise exception will raise java.lang.ClassCastException:
 * java.lang.String cannot be cast to java.lang.Integer.
 */
Map map111 = new TreeMap();
map111.put("one", "krishna");
map111.put("one", "krishna1");
map111.put("two", "munna");
map111.put("three", "balu");
map111.put("four", new Integer(9));// integer as value
// map111.put(new Integer(88), new Integer(99));//integer as key not
// support in Tree Map
Set set1411 = map111.entrySet();
Iterator iterator4111 = set1411.iterator();
while (iterator4111.hasNext()) {
Map.Entry object = (Map.Entry) iterator4111.next();
System.out.println(object.getKey()+ "}}}}}}************}}}"+ object.getValue());

}

No comments:

Post a Comment