0

I'm trying to pass a map with int keys to UI in a json format. I use LinkedHashMap at the server side and compose it as follows:

{
 3: "some value 3",
 1: "some value 1",
 2: "some value 2"
}

But when I check the coming object at the UI side I get the map sorted by key:

{
 1: "some value 1",
 2: "some value 2",
 3: "some value 3"
}

I also tried to use a TreeMap but is works in the same way.

I'm just wondering why the initial order has broken when using int keys whereas the order is preserved when uses not integer keys.

Lyubomyr Shaydariv
  • 18,039
  • 11
  • 53
  • 97
androberz
  • 609
  • 7
  • 23
  • this is not problem of map actually. there is possible scenarios like have you implemented the comparator or comparable interface and used collection's sort method. – Anurag Dadheech Apr 14 '17 at 12:37
  • And which javascript framework you are using?/ – Anurag Dadheech Apr 14 '17 at 12:38
  • You have to deserialize it as `LinkedHashMap` at the UI side as well, because nothing is telling your client that you're passing an ordered map. – Lyubomyr Shaydariv Apr 14 '17 at 12:38
  • Per this answer: http://stackoverflow.com/a/5525820/1712343 , objects do not guarantee order. Your browser chooses to sort integer keys, but this is not guaranteed. Also per that answer, `Map` may suit your needs. – nvioli Apr 14 '17 at 12:45
  • Anurag Dadheech, no matter what comparator I define. By default I use insert ordering in the LinkedHashMap and order is as I expect before passing the map to UI. At the UI I use angular with html. – androberz Apr 14 '17 at 12:54
  • Lyubomyr Shaydariv, I use angular at the front-end and can't use LinkedHashMap from there. – androberz Apr 14 '17 at 12:58
  • @androberz Please tag your question according to your real case, thanks. – Lyubomyr Shaydariv Apr 14 '17 at 13:05

0 Answers0