Java Collections – TreeMap Example

A Red-Black tree based NavigableMap implementation. The TreeMap is sorted according to the natural ordering of its keys, or by a Comparator provided at TreeMap creation time, depending on which constructor is used. In my example, we will be ordering the collection based on employee names.

Big-O Notation

According to the Javadocs, this implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations.

Creating a TreeMap

This was the old-way prior to Generics.

Map employees = new TreeMap();

Generics

If you look closely, you will notice that I am using Generics to limit the type to String for the Key, and Integer for the Value in the Map. Generics add stability to your code, by having the computer detect type incompatibilities during compile-time. These runtime bugs would be more difficult to debug if left unchecked.

Map<String,Integer> employees = new TreeMap<String,Integer>();

Adding elements

Adding elements to the employees Map is done by using the put(Object key, Object value) method. The key of the Map will be the employee name which is a String and the value will be an Integer object. But wait? We are passing an Integer object we are passing an int primitive and Java is not complaining and we did not have to use new Integer(…). Why is this working?

Auto-Boxing and Unboxing

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer and vice-versa without the need to cast. In this case, Java is performing the boxing when we put elements into the map (converting int to Integer wrapper class) and unboxing when we get() elements from the Map (converting Integer to int primitive).

employees.put("John Smith", 85000);
employees.put("David Harvey", 53000);
employees.put("James Young", 103500);
employees.put("Danielle Gray", 94250);
employees.put("Jeff Wang", 76500);
employees.put("Chris Canning", 150000);
employees.put("Mary Anderson", 104100);
employees.put("Tina Mayer", 143700);

Removing elements

Removing elements is just a matter of calling the remove(Object key) method.

employees.remove("Jeff Wang");
employees.remove("Mary Anderson");

Size of Collection

Returning the number of elements in a HashMap is as easy as calling the size() method.

employees.size();

Iterating through the Collection

Java 1.5 and above provides a foreach loop, which makes it much easier to iterate over the entire collection. This is my preferred way of doing it.

// Loop through the collection of employees
for (String name : employees.keySet()) {
   // Get the salary by passing the employee name as the key,
the salary is Auto-UnBoxed
int salary = employees.get(name); }

Iterating through the Collection with Generics

Map<String,Integer> employees = new TreeMap<String,Integer>();
    
Iterator iterator = employees.entrySet().iterator();
while (iterator.hasNext()) {
  Map.Entry<String,Integer> element = (Map.Entry) iterator.next();
  String name = element.getKey();
  int salary = element.getValue();
  System.out.format("Employee==> %-14s | %8dn", name, salary);
}

Iterating through the Collection without Generics

Map employees = new TreeMap();
    
Iterator iterator = employees.entrySet().iterator();
while (iterator.hasNext()) {
  Map.Entry element = (Map.Entry) iterator.next();
  String name = (String) element.getKey();
  int salary = ((Integer)element.getValue()).intValue();
  System.out.format("Employee==> %-14s | %8dn", name, salary);
}

Full Program Listing

package com.avaldes.tutorials;

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

public class HashMapExample {

  public static void main(String[] args) {
    // Ensure that the hashmap only takes String for the key and 
				// Integer for the value
    Map<String,Integer> employees = new TreeMap<String,Integer>();
    
    // Populate the employee hashmap  -- Auto-Boxing 
    employees.put("John Smith", 85000);
    employees.put("David Harvey", 53000);
    employees.put("James Young", 103500);
    employees.put("Danielle Gray", 94250);
    employees.put("Jeff Wang", 76500);
    employees.put("Chris Canning", 150000);
    employees.put("Mary Anderson", 104100);
    employees.put("Tina Mayer", 143700);
    
    System.out.println("Display All Employees -- prior to delete operation");
    displayAllEmployees(employees);
    System.out.println("Number of Employees: " + employees.size());
    
    // Let's remove employee Jeff Wang & Mary Anderson
    System.out.println("nRemoving Jeff Wang from employees");
    employees.remove("Jeff Wang");
    System.out.println("Removing Mary Anderson from employeesn");
    employees.remove("Mary Anderson");
    
    System.out.println("Display All Employees -- after delete operation");
    displayAllEmployees(employees);
    System.out.println("Number of Employees: " + employees.size());
  }
  
  static public void displayAllEmployees(Map<String,Integer> employees) {
    int count = 0;
    
    // Loop through the collection of employees 
    for (String name : employees.keySet()) {
      count++;
      // Get the salary by passing the employee name as the key, the 
						// salary is Auto-UnBoxed
      int salary =  employees.get(name);
      // Format the output nicely
      System.out.format("Employee==> [%d]  %-14s | %8dn", count,name,salary);
    }
  }
}

Output

Display All Employees -- prior to delete operation
Employee==> [1]  Chris Canning  |   150000
Employee==> [2]  Danielle Gray  |    94250
Employee==> [3]  David Harvey   |    53000
Employee==> [4]  James Young    |   103500
Employee==> [5]  Jeff Wang      |    76500
Employee==> [6]  John Smith     |    85000
Employee==> [7]  Mary Anderson  |   104100
Employee==> [8]  Tina Mayer     |   143700
Number of Employees: 8

Removing Jeff Wang from employees
Removing Mary Anderson from employees

Display All Employees -- after delete operation
Employee==> [1]  Chris Canning  |   150000
Employee==> [2]  Danielle Gray  |    94250
Employee==> [3]  David Harvey   |    53000
Employee==> [4]  James Young    |   103500
Employee==> [5]  John Smith     |    85000
Employee==> [6]  Tina Mayer     |   143700
Number of Employees: 6

Other Related Posts

Map Examples

List Examples

Set Examples

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *