TreeMap

Java Sorted Map Example

In this example we shall show you how to make use of Java Sorted Map. A SortedMap is a Map that sort its entries in ascending order according to the keys’ natural ordering, or according to a Comparator provided at the time of the SortedMap creation. All keys inserted into a SortedMap must implement the Comparable interface (or be accepted by the specified Comparator). Furthermore, all such elements must be mutually comparable (i.e, Mutually Comparable simply means that two objects accept each other as the argument to their compareTo method), If you try to sort keys which do not implement Comparable or not has a specific Comparator, a ClassCastException will be thrown.

Tip 1

java.lang.Comparable: int compareTo(Object o):

This method compares this object with o object. Returned int value has the following meanings.

  • positive – this object is greater than o
  • zero – this object equals to o
  • negative – this object is less than o

Also, we can use our own Comparator. If you need to know more about the Comparable and Comparator, Take a look on Java Comparable and Comparator Example to sort Objects by Byron Kiourtzoglou.

Tip 2

All SortedMap implementation classes should provide four “standard” constructors as the following:

  • A void (no arguments) constructor, which creates an empty SortedMap sorted according to the natural ordering of its keys.
    SortedMap sortedMap= new TreeMap();
  • A constructor with a single argument of type Comparator, which creates an empty SortedMap sorted according to the specified Comparator.
    Comparator comparator = new MyComparator();
    SortedMap sortedMap = new TreeMap(comparator);
  • A constructor with a single argument of type Map, which creates a new Map with the same key-value mappings as its argument, sorted according to the keys’ natural ordering.
    Map map = new HashMap();
    SortedMap sortedMap = new TreeMap(map);
  • A constructor with a single argument of type SortedMap, which creates a new SortedMap with the same key-value mappings and the same ordering as the input SortedMap.
    SortedMap sortedMap= new TreeMap();
    SortedMap newSortedMap = new TreeMap(sortedMap);

1. SortedMap Operations:

The SortedMap interface provides operations for normal Map operations and for the following:

  • Range view — performs arbitrary range operations on the SortedMap
    1. subMap(K fromKey, K toKey): Returns a view of the portion of this Map whose keys range from fromKey, inclusive, to toKey, exclusive.
    2. headMap(K toKey): Returns a view of the portion of this Map whose keys are strictly less than toKey.
    3. tailMap(K fromKey): Returns a view of the portion of this Map whose keys are greater than or equal to fromKey.
  • Endpoints — returns the first or the last key in the SortedMap
    1. firstKey(): Returns the first (lowest) key currently in this Map.
    2. lastKey(): Returns the last (highest) key currently in this Map.
  • Comparator access — returns the Comparator, if any, used to sort the map
    1. comparator(): Returns the Comparator used to order the keys in this Map, or null if this Map uses the natural ordering of its keys.

2. Example:

2.1. SortMapExample.java

package com.jcg.util.map;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author ashraf
 * 
 */
public class SortMapExample {

	/**
	 * The main method.
	 *
	 * @param args the arguments
	 */
	public static void main(String[] args) {
		//creating unsorted map of employee id as a key and employee name as a value
		Map unsortMap = new HashMap();
		unsortMap.put(10, "Ashraf");
		unsortMap.put(5, "Sara");
		unsortMap.put(6, "Mohamed");
		unsortMap.put(20, "Esraa");
		unsortMap.put(1, "Bahaa");
		unsortMap.put(7, "Dalia");
		unsortMap.put(8, "Amira");
		unsortMap.put(99, "Ahmed");
		unsortMap.put(50, "Sama");
		unsortMap.put(2, "Nada");
		unsortMap.put(9, "Osama");

		System.out.println("Unsort Map......");
		printMap(unsortMap);

		// Using the default natural ordering of sorted map Integer key which implement Comparable interface
		System.out.println("\nSorted Map in ascending order......");
		Map ascSortedMap = new TreeMap();
		ascSortedMap.putAll(unsortMap);
		printMap(ascSortedMap);

		// Forcing the descending order by creating our own comparator then passing it to the sorted map at creation time
		System.out.println("\nSorted Map in descending order......");
		Map desSortedMap = new TreeMap(
				new Comparator() {

					@Override
					public int compare(Integer o1, Integer o2) {
						return o2.compareTo(o1);
					}

				});
		desSortedMap.putAll(unsortMap);
		printMap(desSortedMap);

	}

	/**
	 * Prints the map.
	 *
	 * @param map the map
	 */
	public static void printMap(Map map) {
		for (Map.Entry entry : map.entrySet()) {
			System.out.println("Key : " + entry.getKey() + " Value : "
					+ entry.getValue());
		}
	}

}

2.2. Explanation:

Let’s suppose that we want to sort a Map which contains a group of employees according to their ids where we use the employee id as a key and the employee name as a value. After we create a SortedMap using this Map and the key of this Map is an Integer type which implements the Comparable interface, the keys are ordered in their natural ordering. Also, we can apply the descending order by creating our own Comparator then passing it to the SortedMap at creation time.

2.3. Output:

Unsort Map......
Key : 50 Value : Sama
Key : 1 Value : Bahaa
Key : 2 Value : Nada
Key : 99 Value : Ahmed
Key : 20 Value : Esraa
Key : 5 Value : Sara
Key : 6 Value : Mohamed
Key : 7 Value : Dalia
Key : 8 Value : Amira
Key : 9 Value : Osama
Key : 10 Value : Ashraf

Sorted Map in ascending order......
Key : 1 Value : Bahaa
Key : 2 Value : Nada
Key : 5 Value : Sara
Key : 6 Value : Mohamed
Key : 7 Value : Dalia
Key : 8 Value : Amira
Key : 9 Value : Osama
Key : 10 Value : Ashraf
Key : 20 Value : Esraa
Key : 50 Value : Sama
Key : 99 Value : Ahmed

Sorted Map in descending order......
Key : 99 Value : Ahmed
Key : 50 Value : Sama
Key : 20 Value : Esraa
Key : 10 Value : Ashraf
Key : 9 Value : Osama
Key : 8 Value : Amira
Key : 7 Value : Dalia
Key : 6 Value : Mohamed
Key : 5 Value : Sara
Key : 2 Value : Nada
Key : 1 Value : Bahaa

3. Download the Source Code of this example:

This was an example of how to use Java Sorted Map.

Download
You can download the full source code of this example here: Java Sorted Map Example Code

Ashraf Sarhan

Ashraf Sarhan is a passionate software engineer, an open source enthusiast, has a Bsc. degree in Computer and Information Systems from Alexandria University. He is experienced in building large, scalable and distributed enterprise applications/service in multiple domains. He also has a keen interest in JavaEE, SOA, Agile and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button