Java/J2EE and SOA (348 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (345 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

A Brief Introduction to TreeMap in Java with Examples

Published on Aug 20,2019 2.7K Views


Implementing a Map interface in Java is a very important task. For this purpose, we have TreeMap and HashMap. In this article our focus will be on TreeMap in Java in the Following Order:

 

What is a TreeMap in Java?

A TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-value pairs.

TreeMap-in-JavaThe storing order maintained by the treemap must be consistent with equals just like any other sorted map, irrespective of the explicit comparators. The treemap implementation is not synchronized in the sense that if a map is accessed by multiple threads, concurrently and at least one of the threads modifies the map structurally, it must be synchronized externally.

 

Features of TreeMaps

  • This class is a member of the Java Collections Framework.

  • The class implements Map interfaces including NavigableMap, SortedMap and extends AbstractMap

  • TreeMap in Java does not allow null keys (like Map) and thus a NullPointerException is thrown. However, multiple null values can be associated with different keys.

  • All Map.Entry pairs returned by methods in this class and its views represent snapshots of mappings at the time they were produced.

  • They do not support the Entry.setValue method.

 

Important Points to Remember

  1. Apart from implementing the Map interface, Java TreeMap also implements NavigableMap and indirectly implements SortedMap interface. TreeMap also extends AbstractMap class.

  2. TreeMap entries are sorted in the natural ordering of its keys. It also provides a constructor to provide Comparator to be used for ordering. So if you are using any class as key, make sure it’s implementing Comparable interface for natural ordering. Check out java collections interview questions to understand the importance of these methods.

  3. Java TreeMap implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

  4. TreeMap is not synchronized and hence not thread-safe. For multithreaded environments, you can get a wrapped synchronized using Collections.synchronizedSortedMap method.

  5. TreeMap methods to get keyset and values return Iterator that is fail-fast in nature, so any concurrent modification will throw ConcurrentModificationException.

  6. TreeMap in java doesn’t allow null keys, however, you can have multiple null values associated with different keys.

 

Constructors in TreeMap

ConstructorDescription
TreeMap( )Constructs an empty treemap that will be sorted using the natural order of its keys.
TreeMap(Comparator comp)Constructs an empty tree-based map that will be sorted using the Comparator comp.
TreeMap(Map m)Initializes a treemap with the entries from m, which will be sorted using the natural order of the keys.
TreeMap(SortedMap sm)Initializes a treemap with the entries from the SortedMap sm, which will be sorted in the same order as sm.

 

Methods in TreeMap

Method Description
void clear()Removes all mappings from this TreeMap.
Object clone()Returns a shallow copy of this TreeMap instance.
Comparator comparator()Returns the comparator used to order this map, or null if this map uses its keys’ natural order.
boolean containsKey(Object key)Returns true if this map contains a mapping for the specified key.
boolean containsValue(Object value)Returns true if this map maps one or more keys to the specified value.
Set entrySet()Returns a set view of the mappings contained in this map.
Object firstKey()Returns the first (lowest) key currently in this sorted map.
Object get(Object key)Returns the value to which this map maps the specified key.
SortedMap headMap(Object toKey)Returns a view of the portion of this map whose keys are strictly less than toKey.
Set keySet()Returns a Set view of the keys contained in this map.
Object lastKey()Returns the last (highest) key currently in this sorted map.
Object put(Object key, Object value)Associates the specified value with the specified key in this map.
void putAll(Map map)Copies all of the mappings from the specified map to this map.
Object remove(Object key)Removes the mapping for this key from this TreeMap if present.
int size()Returns the number of key-value mappings in this map.
SortedMap subMap(Object fromKey, Object toKey)Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.
SortedMap tailMap(Object fromKey)Returns a view of the portion of this map whose keys are greater than or equal to fromKey.
Collection values()Returns a collection view of the values contained in this map.

 

Example of TreeMap in Java

import java.util.TreeMap;
 
public class TreeMapMain {
 
	public static void main(String args[])
	{
		// TreeMap with Country as key and capital as value
		// TreeMap stores elements in natural ordering of keys.
		TreeMap<String,String> countryCapitalMap=new TreeMap<String,String>();
		countryCapitalMap.put("India","Delhi");
		countryCapitalMap.put("Japan","Tokyo");
		countryCapitalMap.put("France","Paris");
		countryCapitalMap.put("Russia","Moscow");
 
		System.out.println("-----------------------------");
		// Iterating TreeMap Using keySet() and for each loop
		System.out.println("Iterating TreeMap Using keySet() and for each loop");
		for (String countryKey:countryCapitalMap.keySet()) {
			System.out.println("Country:"+ countryKey +" and  Capital:"+countryCapitalMap.get(countryKey));
 
		}
		System.out.println("-----------------------------");
	}
 
}

Output:

Output-TreeMap

With this, we come to an end of this TreeMap in Java article. Check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “TreeMap in Java” blog and we will get back to you as soon as possible.

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 4th May,2024

4th May

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 25th May,2024

25th May

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

A Brief Introduction to TreeMap in Java with Examples

edureka.co