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 ozero
– this object equals to onegative
– 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 emptySortedMap
sorted according to the specifiedComparator
.Comparator comparator = new MyComparator(); SortedMap sortedMap = new TreeMap(comparator);
- A constructor with a single argument of type
Map
, 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 type
SortedMap
, 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:
The SortedMap
interface provides operations for normal Map operations and for the following:
- Range view — performs arbitrary range operations on the
SortedMap
subMap(K fromKey, K toKey)
: Returns a view of the portion of thisMap
whose keys range from fromKey, inclusive, to toKey, exclusive.headMap(K toKey)
: Returns a view of the portion of thisMap
whose keys are strictly less than toKey.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
- Comparator access — returns the
Comparator
, if any, used to sort the mapcomparator()
: 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 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.
You can download the full source code of this example here: Java Sorted Map Example Code