Java - Use Comparator object to sort the entries based keys in a SortedMap

Introduction

You need use the constructor of the TreeMap class that takes a Comparator as an argument.

The following code sorts entries in a sorted map based on the length of their keys followed by the alphabetical order of the keys ignoring the case.

Demo

import java.util.Comparator;
import java.util.SortedMap;
import java.util.TreeMap;

public class Main {
  public static void main(String[] args) {
    // Sort entries on key's length and then on keys ignoring case
    Comparator<String> keyComparator = Comparator.comparing(String::length)
        .thenComparing(String::compareToIgnoreCase);
    SortedMap<String, String> sMap = new TreeMap<>(keyComparator);
    sMap.put("XML", "(342)113-1234");
    sMap.put("Javascript", "(245)890-2345");
    sMap.put("Json", "(205)678-3456");
    sMap.put("Java", "(205)678-3456");
    sMap.put("Zee", "(205)679-3456");

    System.out.println("Sorted Map: " + sMap);
  }/*w ww.ja  v  a 2s. com*/
}

Result

Related Topic