Subscribe To MegiSoft RSS Feeds!     Your Browser OR  Google Feedburner

Java TreeMap

TreeMap is one of the classes of the Java standard library. It is a subclass of the class AbstractMap and implements the interfaces Map<K,V>, SortedMap<K,V>,  NavigableMap<K,V>Serializable, Cloneable.

The following UML diagram shows the position of the class TreeMap in the hierarchy.

Articles: ArrayList  HashSet  TreeSet  HashMap  TreeMap 
Quizzes: Java Collection Quizzes 

treemap-hierarchy

What is a TreeMap in Java?

A TreeMap is a data structure that allows you to collect elements. It is one of the classes in the Java library, which contains different methods to add, remove elements and more. Each element of a TreeMap has a key and a vlaue.  To use it in your own classes, you need to import the package “java.util” from the Java library  as shown below.

java.util.TreeMap<K,V>;

 

Is TreeMap my best Java collection class choice?

To answer the question whether TreeMap is your best choice,you need to know more details about it as well as about other Java collection classes. The information and the exercises below will help you to make that decision.

  1. TreeMap implements Map as well as SortedMap interfaces.
  2. The map is sorted based on its keys,
  3. A TreeMap key is unique.
  4. You can add elements to a TreeMap based on a Key and a Value by using the method put(key, value).
  5. It is not synchronized.

Exercise 1A: How to create a Java TreeMap and add elements to it?

  • Create a TreeMap “studentMap” and add the following students and their scores to it:Anouk A 10, Anouk B 8, Ronan 4, Mabel 9, Hugo 8, Harry 7, Lily 8, Vincent 6, Eva 6, George 8, Ruby 10, Alexandra 4, Michael 8.

 

Exercise 1B: How to find the size of a Java TreeMap?

  • Print the size of the TreeMap to the standard output before and after adding the students.

Answer 1

  • a. The following code adds the mentioned students and their scores to the TreeMap studentMap.
  • b. The program writes the following to the standard output when it is compiled and run.

TreeMap size before entries: 0
TreeMap size after entries: 13

import java.util.TreeMap;

public class TestTreeMap {

	public static void main(String[] args){

		TreeMap<String,Integer> studentMap = new TreeMap<String,Integer>();
		System.out.println("TreeMap size before entries: " + studentMap.size());

		studentMap.put("Anouk A",new Integer(10));
		studentMap.put("Anouk B",new Integer(8));
		studentMap.put("Ronan",new Integer(4));
		studentMap.put("Mabel",new Integer(9));
		studentMap.put("Hugo",new Integer(8));
		studentMap.put("Harry",new Integer(7));
		studentMap.put("Lily",new Integer(8));
		studentMap.put("Vincent",new Integer(6));
		studentMap.put("Eva",new Integer(6));
		studentMap.put("George",new Integer(8));
		studentMap.put("Ruby",new Integer(10));
		studentMap.put("Alexandra",new Integer(4));
		studentMap.put("Michael",new Integer(8));
		System.out.println("TreeMap size after entries: " + studentMap.size());
	}
}

Please, leave your questions, feedback and suggestions in the comments below! If you need more explanation by any of the answers, just let me know to update it for you!

Exercise 2: How to retrieve the elements of a Java TreeMap and print them to the standard output?

  • Add a piece of code to the exercise 1 to retrieve and print all the student names who scored 8 to the standard output.

Answer 2

  • When the program is compiled and run, it writes the following to the standard output.

Anouk B: 8
George: 8
Hugo: 8
Lily: 8
Michael: 8

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

public class TestTreeMap {

	public static void main(String[] args){

		TreeMap<String,Integer> studentMap = new TreeMap<String,Integer>();
		studentMap.put("Anouk A",new Integer(10));
		studentMap.put("Anouk B",new Integer(8));
		studentMap.put("Ronan",new Integer(4));
		studentMap.put("Mabel",new Integer(9));
		studentMap.put("Hugo",new Integer(8));
		studentMap.put("Harry",new Integer(7));
		studentMap.put("Lily",new Integer(8));
		studentMap.put("Vincent",new Integer(6));
		studentMap.put("Eva",new Integer(6));
		studentMap.put("George",new Integer(8));
		studentMap.put("Ruby",new Integer(10));
		studentMap.put("Alexandra",new Integer(4));
		studentMap.put("Michael",new Integer(8));

		// display the TreeMap content using Iterator
		Set<Entry<String,Integer>> set = studentMap.entrySet();
		Iterator iter = set.iterator();
		// retrieve the names of the students who scored 8
		while(iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			if(entry.getValue().equals(8)) {
				System.out.println(entry.getKey() + ": " + entry.getValue());
			}
		}
	}
}

Please, leave your questions, feedback and suggestions in the comments below! If you need more explanation by any of the answers, just let me know to update it for you!

Articles: ArrayList  HashSet  TreeSet  HashMap  TreeMap 
Quizzes: Java Collection Quizzes 
Megisoft.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes. The author of Megisoft is Sar Maroof who has more than a decade of experience with web development mainly with Java, MySql, HTML and more..

Suggested Articles:


Click Here For Info about: Sar Maroof's New Java Book
Author: Sar Maroof
More than a decade of experience with developing web applications mainly with Java.
Sun Certified JSP as well as EJB
CIW Certified Internet Webmaster - Mind IT
Applied Science in Physics HBO Amsterdam
Bachellor Science in Physics at Basra university.
 Subscribe To Megisoft RSS Feeds! (Your Browser)
 Mail This Page To A Friend!
 Bookmark This Page!
Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

Leave a Reply

megisoft © 2016