1

I am using a LinkedHashMap to store map entries sorted by some business rule and I am sending it to the client, but my AJAX response always gets sorted by the map key.

My sort function:

protected Map<Long, String> sortWarehousesMap(Map<Long, String> warehousesMapTemp) {
    List<Map.Entry<Long, String>> entries = new ArrayList<Map.Entry<Long, String>>(warehousesMapTemp.entrySet());

    Collections.sort(entries, new Comparator<Map.Entry<Long, String>>() {

        public int compare(Map.Entry<Long, String> a, Map.Entry<Long, String> b) {
            return a.getValue().compareTo(b.getValue());
        }
    });
    Map<Long, String> sortedWarehousesMapTemp = new LinkedHashMap<Long, String>();
    for (Map.Entry<Long, String> entry : entries) {
        sortedWarehousesMapTemp.put(entry.getKey(), entry.getValue());
    }
    return sortedWarehousesMapTemp;
}

Please help me what am I doing wrong.

Boann
  • 44,932
  • 13
  • 106
  • 138
user2375298
  • 851
  • 4
  • 12
  • 25

2 Answers2

2

I've had the same problem and it didn't happen in FF.
The problem is that the returned map is interpreted as array.
The key of your map is a Long (the same if you use String but with integer value, like "5" for example) so the result is an Array.
My solution has been to add an "_" in front of the key in order to have a fake key.

Luca Rasconi
  • 906
  • 9
  • 25
1

You mention an AJAX response, so I'm assuming that at some point this is being translated into a JSON representation. As you're using a Map this is going to be converted into a JSON object, and unfortunately the JSON specification makes no guarantees as to the order of properties in an object (see Does JavaScript Guarantee Object Property Order?), it is literally unspecified. Whichever library you are using to convert between Java objects and a JSON representation is probably sorting the keys for you.

If you absolutely must preserve the order of something in JSON, you'll have to use a JSON array.

Community
  • 1
  • 1
Ross Taylor-Turner
  • 3,549
  • 2
  • 23
  • 32
  • Java library doesn't sort the keys (see for example Jackson JSON processor). It's the browser (while parsing the string from server) that doesn't build the JSON as you expected. – Luca Rasconi Nov 25 '14 at 13:53
  • It's true that Jackson doesn't reorder the keys (and will indeed return them in the order in the JSON) but the OP didn't specify they're using Jackson so I decided to leave that out of the answer. It's possible a JSON Java library is in use which does sort the keys this way. Chrome and Firefox both don't re-order the keys **except** when viewing them in dev tools, so it's possible to use Jackson with an ordered map and process the keys in that same order, although it is not guaranteed so it's not a good idea unless you can be sure which browser(s) all your users have. – Ross Taylor-Turner Nov 25 '14 at 14:48