How to sort order of map.keySet() in Java?

1.4k Views Asked by At
public class MapKeyExample {
    public static void main(String[] args){

        //Initializing a Map of type HashMap
        Map<Integer, String> map = new HashMap<>();
        Set<Integer> s = new HashSet<>();
        map.put(1, "One");
        map.put(3, "Three");
        map.put(5, "Five");
        map.put(7, "Seven");
        map.put(9, "Nine");
        System.out.println(map);
        s = map.keySet();
        System.out.println(s);
    }
}

Now the output is

{1=One, 3=Three, 5=Five, 7=Seven, 9=Nine}
[1, 3, 5, 7, 9]

The expected output of s is:

[1, 5, 3, 9, 7]

Can someone show me how to modify this to Linkedhashmap or treemap? Many thanks.

2

There are 2 best solutions below

0
Emily On BEST ANSWER

It's not exactly clear what you mean by "change it to the order I want".

However, Java provides these options:

  • A LinkedHashMap can be iterated over in the same order you inserted the entries in.
  • TreeMap's constructor allows you to provide a Comparator, which will define the order of the keys.
4
mentallurg On

The order of key is undefined for the most types of maps. Sorting of keys is supported in the TreeMap. In your case the default order (the natural order of Integer) will be sufficient. To produce your own order, implement corresponding comparator.

public class MyComparator implements Comparator<Integer> {
    public int compare(Integer i1, Integer i2) {
        ...
        // If i1 should be before i2, return -1
        // If i1 should be after i2, return 1
        // Otherwise return 0
    }
}