-2
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.

snieguu
  • 2,073
  • 2
  • 20
  • 39
Cecilia
  • 309
  • 2
  • 12
  • Use `SortedMap` instead of `HashMap`. – mentallurg Oct 27 '19 at 20:18
  • 2
    Can you explain the expected output? What pattern does it follow? – Marvin Oct 27 '19 at 20:19
  • @Marvin no pattern because I want to specify the order and change it to the order I want, I tried TreeMap but it gives me the natural order of integer. – Cecilia Oct 27 '19 at 20:22
  • 3
    @Cecilia It does not make sense to ask "can you show how to make this into the order I want" if you can't explain what is the order you want – eis Oct 27 '19 at 20:35

2 Answers2

4

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.
Emily
  • 1,030
  • 1
  • 12
  • 20
0

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
    }
}
mentallurg
  • 4,967
  • 5
  • 28
  • 36
  • I don't want it to be natural oder, is there a way that I can specify the order and change it to the order I want, I tried TreeMap but it gives me the natural order of integer. – Cecilia Oct 27 '19 at 20:23
  • 1
    You can implement your own comparator and use it as argument when you create TreeMap. In this comparator implement the logic that produces the order that you need. – mentallurg Oct 27 '19 at 20:26
  • 1
    I'm very new to Java, do you mind showing me an example. Many thanks. – Cecilia Oct 27 '19 at 20:30
  • See updated answer. – mentallurg Oct 27 '19 at 20:43