Sort Map values in ascending key order in Java TreeMap

Overview

--The HashMap class, a popular implementation of the Map interface, does not guarantee any ordering. --The SortedMap interface provides key ordering --The TreeMap class implements the SortedMap interface, so key ordering is done. --If you use the TreeMap class, the keys are automatically sorted in ascending order.

HashMap class

HashMap doesn't sort anything.

HashMap (Java SE 11 & JDK 11 )

This class does not guarantee the order of the maps. In particular, we do not guarantee that the order will always be constant.

SortedMap interface

SortedMap realizes sorting by key. The keys and values returned by the entrySet, keySet, and values methods are sorted according to the key order.

SortedMap (Java SE 11 & JDK 11 )

A Map that provides global ordering for that key. Map ordering can be done according to the natural ordering of the keys, or with the Comparator normally provided when building the sort map. This order is reflected during iterative processing of the sort map collection view (returned by the entrySet, keySet, values methods). Some additional operations are provided to take advantage of that ordering. (This interface is a map and is similar to SortedSet.)

TreeMap class

TreeMap implements the SortedMap interface, so key sorting is done.

TreeMap (Java SE 11 & JDK 11 )

Red-NavigableMap implementation based on black tree. Maps are sorted according to the constructor used, according to the natural ordering of their keys, or by the Comparator provided at map creation.

Sample code

Source code to check the behavior of HashMap and TreeMap.

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

public class Sample {

  public static void main(String[] args) {

    //Build HashMap
    //Order is not guaranteed
    Map<String, String> hashMap = new HashMap<String, String>();
    hashMap.put("0001", "Alice");
    hashMap.put("0002", "Bob");
    hashMap.put("0003", "Carol");
    hashMap.put("0004", "Dave");
    hashMap.put("0005", "Ellen");
    System.out.println("HashMap");
    for (String key : hashMap.keySet()) {
      System.out.println(key + ": " + hashMap.get(key));
    }
    System.out.println();

    //Build a TreeMap
    //It sorts automatically in ascending order of keys
    Map<String, String> treeMap = new TreeMap<String, String>(hashMap);
    System.out.println("TreeMap");
    for (String key : treeMap.keySet()) {
      System.out.println(key + ": " + treeMap.get(key));
    }
    System.out.println();

    //When you add a value to the TreeMap, it will automatically sort in ascending key order.
    treeMap.put("0000", "XXXXX");
    System.out.println("TreeMap");
    for (String key : treeMap.keySet()) {
      System.out.println(key + ": " + treeMap.get(key));
    }
    System.out.println();
  }
}

Execution result. HashMap doesn't sort anything. TreeMaps are sorted in ascending key order.

HashMap
0004: Dave
0005: Ellen
0002: Bob
0003: Carol
0001: Alice

TreeMap
0001: Alice
0002: Bob
0003: Carol
0004: Dave
0005: Ellen

TreeMap
0000: XXXXX
0001: Alice
0002: Bob
0003: Carol
0004: Dave
0005: Ellen

This environment

$ java --version
openjdk 11.0.2 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)

Recommended Posts

Sort Map values in ascending key order in Java TreeMap
Get Null-safe Map values in Java
Sorting in ascending order in Java (bubble sort: simple exchange algorithm)
Duplicate Map sorted by key in Java
Reverse Key from Value in Java Map
[Java] HashMap, TreeMap, LinkedHashMap set values retention order
[java] sort in list
How to sort in ascending / descending order with SQLite
Get location information in Rails and sort in ascending order
[Neta] Sleep Sort in Java
[Java8] Sort int type array in descending order using stream
Sort List in descending order in Java and generate a new List non-destructively
I tried to sort the data in descending order, ascending order / Rails
Use composite keys in Java Map.
Member description order in Java coding convention
Key points for introducing gRPC in Java
Map without using an array in java
Implemented basic search / sort algorithm in Java
[Java] Be careful of the key type of Map
[Java] How to get the key and value stored in Map by iterative processing