TreeMap in Java

In the previous post, we have learnt about LinkedHashMap. In this post, we will learn about TreeMap in java.

It has the following features as given below.

  • It implements the NavigableMap interface and extends AbstractMap class.
  • It contains only unique values.
  • It can not have null key but can have multiple null values.
  • It sorts the Map in ascending order.
  • TreeMap is unsynchronized collection class which means it is not suitable for thread-safe operations until unless synchronized explicitly.

Let’s understand this with the Example.

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class HashMapEx {

	public static void  main(String[] args){
		
		TreeMap<Integer,String> hm = new TreeMap<Integer,String>();
		hm.put(15, "Mobile");
		hm.put(6, "TV");
		hm.put(10, "Laptop");
		hm.put(2, "Desktop");
		hm.put(1, "Tablet");
		hm.put(23, "Microphone");
		
		Iterator iter = hm.entrySet().iterator();
		while(iter.hasNext()){
			Map.Entry m = (Entry) iter.next();
			//Maintains ascending order
			System.out.println(m.getKey()+"--"+m.getValue()); 
		}
		
	}
}

Output:

1–Tablet
2–Desktop
6–TV
10–Laptop
15–Mobile
23–Microphone


Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".