0

Lets say, I have a map as Map<String, String> data = new HashMap<String, String>();

I have following keys of this map

{benefits7,benefits11,benefits1,benefits10,benefits15};

And I need it to sort these keys as following:

{benefits1,benefits7,benefits10,benefits11,benefits15}

Can anyone help please?

Kum
  • 333
  • 7
  • 20
  • 2
    http://stackoverflow.com/questions/922528/how-to-sort-map-values-by-key-in-java can help you – Wilson Jul 01 '16 at 10:11
  • @Kum You need to elaborate a bit here. Why would you want to use a map, and then sort the keys.? Did you try using a Tree Map instead? – Amal Gupta Jul 01 '16 at 10:13

3 Answers3

0

Can't you use SortedMap instead HashMap?

This way if you iterate over the map by using entrySet or KeySet it will return your values sorted by its key.

By default it use the natural ordering for your key's class (String in your example), and this behaviour seems enough for your requirements

Here is the SortedMap API

SCouto
  • 7,808
  • 5
  • 32
  • 49
0

Can you try this ?

Map<String, String> data = new HashMap<String, String>();
Set<String> keys = data.keySet();
Set<String> sortedKeys = Collections.sort(keys);
Mickael
  • 4,458
  • 2
  • 28
  • 40
0

You can use a list to sort the keys. If you need to have order in your map, then you should not use a HashMap as it doesn't care about order.

Use a linked hash map instead. So, you could have an ordered list of keys:

List<String> keys = new ArrayList<String>(data.keySet());
Collections.sort(keys);

If you want to iterate over the map according to the order of your keys, then use a java.util.LinkedHashMap, instead of a HashMap. But you would have to put elements according to the explicit order as shown above.

ernest_k
  • 44,416
  • 5
  • 53
  • 99