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.
It's not exactly clear what you mean by "change it to the order I want".
However, Java provides these options:
TreeMap
's constructor allows you to provide a Comparator
, which will define the order of the keys.