Java Example – Simple Java TreeMap example

Java Tutorial for Beginners
Java Tutorial for Beginners
Java Tutorial for Beginners
Java Tutorial for Beginners

In this Java Example we will see how to use Java TreeMap. It example also describes how to add elements to TreeMap and how to retrieve the value added from TreeMap.
TreeMap implementation

  • Uses a Red – Black tree to implement a Map
  • relies on the compareTo method of the keys
  • somewhat slower than the HashMap
  • keys stored in sorted order

We can add key value pair to TreeMap using Object put(Object key, Object value) method of Java TreeMap class, where key and value both are objects put method returns Object which is either the value previously tied to the key or null if no value mapped to the key.

Please note that put method accepts Objects. Java Primitive values CAN NOT be added directly to TreeMap. It must be converted to corresponding wrapper class first.


  Simple Java TreeMap example by 

import java.util.TreeMap;

public class JavaTreeMapExample {

    public static void main(String[] args) {

        //create object of TreeMap
        TreeMap treeMap = new TreeMap();

     * treeMap.put Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.

        treeMap.put("One", new Integer(1));
        treeMap.put("Two", new Integer(2));

        //retrieve value using Object get(Object key) method of Java TreeMap class
        Object objOne = treeMap.get("One");
        Object objTwo = treeMap.get("Two");

      Please note that the return type of get method is an Object. The value must
      be casted to the original class.


Partner Sites

1 Comment

Leave a Reply

Your email address will not be published.