TreeMap

Java Sorted Map Example

Photo of Ashraf SarhanAshraf SarhanAugust 22nd, 2014Last Updated: August 22nd, 2014
0 461 4 minutes read

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 ownComparator. If you need to know more about theComparable andComparator, Take a look onJava Comparable and Comparator Example to sort Objects byByron Kiourtzoglou.

Tip 2

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

  • A void (no arguments) constructor, which creates an emptySortedMap sorted according to the natural ordering of its keys.
    SortedMap sortedMap= new TreeMap();
  • A constructor with a single argument of typeComparator, which creates an emptySortedMap sorted according to the specifiedComparator.
    Comparator comparator = new MyComparator();SortedMap sortedMap = new TreeMap(comparator);
  • A constructor with a single argument of typeMap, which creates a newMap 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 typeSortedMap, which creates a newSortedMap with the same key-value mappings and the same ordering as the inputSortedMap.
    SortedMap sortedMap= new TreeMap();SortedMap newSortedMap = new TreeMap(sortedMap);

1. SortedMap Operations:

TheSortedMap 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 thisMap whose keys range from fromKey, inclusive, to toKey, exclusive.
    2. headMap(K toKey): Returns a view of the portion of thisMap whose keys are strictly less than toKey.
    3. tailMap(K fromKey): Returns a view of the portion of thisMap 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 thisMap.
    2. lastKey(): Returns the last (highest) key currently in thisMap.
  • Comparator access — returns theComparator, if any, used to sort the map
    1. comparator(): Returns theComparator used to order the keys in thisMap, or null if thisMap 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 valueMap 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 interfaceSystem.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 timeSystem.out.println("\nSorted Map in descending order......");Map desSortedMap = new TreeMap(new Comparator() {@Overridepublic 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 aMap 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 aSortedMap using thisMap and the key of thisMap is anInteger type which implements the Comparable interface, the keys are ordered in their natural ordering. Also, we can apply the descending order by creating our ownComparator then passing it to theSortedMap at creation time.

2.3. Output:

Unsort Map......Key : 50 Value : SamaKey : 1 Value : BahaaKey : 2 Value : NadaKey : 99 Value : AhmedKey : 20 Value : EsraaKey : 5 Value : SaraKey : 6 Value : MohamedKey : 7 Value : DaliaKey : 8 Value : AmiraKey : 9 Value : OsamaKey : 10 Value : AshrafSorted Map in ascending order......Key : 1 Value : BahaaKey : 2 Value : NadaKey : 5 Value : SaraKey : 6 Value : MohamedKey : 7 Value : DaliaKey : 8 Value : AmiraKey : 9 Value : OsamaKey : 10 Value : AshrafKey : 20 Value : EsraaKey : 50 Value : SamaKey : 99 Value : AhmedSorted Map in descending order......Key : 99 Value : AhmedKey : 50 Value : SamaKey : 20 Value : EsraaKey : 10 Value : AshrafKey : 9 Value : OsamaKey : 8 Value : AmiraKey : 7 Value : DaliaKey : 6 Value : MohamedKey : 5 Value : SaraKey : 2 Value : NadaKey : 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
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Ashraf SarhanAshraf SarhanAugust 22nd, 2014Last Updated: August 22nd, 2014
0 461 4 minutes read
Photo of Ashraf Sarhan

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
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.