Java - TreeMap example

Posted on October 24, 2016


TreeMap class implements the Map interface similar to the HashMap. TreeMap is an example of SortedMap i.e. the order of keys can be sorted.

In the below example, we will show you various methods of TreeMap class.

  • put() - add key and value into the Map.
  • get() - return value by passing key.
  • remove() - delete key and value  from the map.
  • size() - return size of map.
  • containsKey() - return true if key exist in map otherwise return false.
  • containsValue() - return true if value exist in map otherwise return false.
  • clear() - remove all elements from map

TreeMapExample.java

package com.boraji.tutorial;

import java.util.Map;
import java.util.TreeMap;

/**
 * @author imssbora
 *
 */
public class TreeMapExample {
	public static void main(String[] args) {
		Map<String, String> map=new TreeMap<>();
		/*Adding key and values in TreeMap*/
		map.put("1", "One");
		map.put("2", "Two");
		map.put("3","Three");
		map.put("4", "Four");
		map.put("5", "Five");
		
		System.out.println("TreeMap key-values:"+map);
		
		/*Get value by key from the TreeMap*/
		System.out.println("Value of '4' is: "+map.get("4"));
		
		/*Removing key and value from the TreeMap	*/
		map.remove("4");
		System.out.println("After removal, TreeMap Key-Value: " +map);
		
		/*Getting size of TreeMap*/
		System.out.println("Size of TreeMap is : "+map.size());
		
		/*Checking if key exist in the TreeMap or not*/
		System.out.println("Key '3' exist: "+map.containsKey("3"));
		
		/*Checking if value exist in the TreeMap or not*/
		System.out.println("Key '6' exist: "+map.containsValue("6"));
		
		/*Remove all keys and values from the TreeMap*/
		map.clear();
		System.out.println("After clearing map: "+map);
	}
}

Output

TreeMap key-values:{1=One, 2=Two, 3=Three, 4=Four, 5=Five}
Value of '4' is: Four
After removal, TreeMap Key-Value: {1=One, 2=Two, 3=Three, 5=Five}
Size of TreeMap is : 4
Key '3' exist: true
Key '6' exist: false
After clearing map: {}