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 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 empty
SortedMapsorted according to the natural ordering of its keys.SortedMap sortedMap= new TreeMap();
- A constructor with a single argument of type
Comparator, which creates an emptySortedMapsorted 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 newMapwith 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 newSortedMapwith 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
SortedMapsubMap(K fromKey, K toKey): Returns a view of the portion of thisMapwhose keys range from fromKey, inclusive, to toKey, exclusive.headMap(K toKey): Returns a view of the portion of thisMapwhose keys are strictly less than toKey.tailMap(K fromKey): Returns a view of the portion of thisMapwhose 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 theComparatorused to order the keys in thisMap, or null if thisMapuses 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.
You can download the full source code of this example here:Java Sorted Map Example Code

Thank you!
We will contact you soon.



