Java sort HashMap by key.

public static void main(String[] args) throws Exception {
    Map<Integer, String> map = new HashMap<>();
    map.put(32, "ruby");
    map.put(111, "c++");
    map.put(22, "python");
    map.put(50, "java");

    System.out.println("###### by default hash map is un-ordered ######");
    map.forEach((k, v) -> {
        System.out.println("k = " + k + ", v = " + v);
    });

    System.out.println("###### sort by key in ascending order (default) ######");
    Map<Integer, String> sortedMapByKeyAsc = new TreeMap<>(map);
    sortedMapByKeyAsc.forEach((k, v) -> {
        System.out.println("k = " + k + ", v = " + v);
    });

    System.out.println("###### sort by key in descending order (custom) ######");
    Map<Integer, String> sortedMap = new TreeMap<>((k1, k2) -> k2 - k1);
    sortedMap.putAll(map);
    sortedMap.forEach((k, v) -> {
        System.out.println("k = " + k + ", v = " + v);
    });
}

// output
// ###### by default hash map is un-ordered ######
// k = 32, v = ruby
// k = 50, v = java
// k = 22, v = python
// k = 111, v = c++
// ###### sort by key in ascending order (default) ######
// k = 22, v = python
// k = 32, v = ruby
// k = 50, v = java
// k = 111, v = c++
// ###### sort by key in descending order (custom) ######
// k = 111, v = c++
// k = 50, v = java
// k = 32, v = ruby
// k = 22, v = python
TOPâ–˛
Post tagged with: java