3

I use HashMaps for storing sets of pairs, but I also have to be sure from the first json serialization (from a Php client) and to the Java HashMap set browsing, the order of keys will be the same

//import com.google.gson.Gson;
//import com.google.common.base.Joiner;  
String s = "{\"durant\":\"kevin\", \"james\":\"lebron\",\"harden\":\"james\",\"westbrook\":\"russel\"}";
System.out.println(s);
Gson gson = new Gson();
Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
Map<String, String> m = gson.fromJson(s, typeOfMap);
List<String> entries = new ArrayList< String>(m.keySet());
//Collections.sort(entries);
System.out.println(entries);
System.out.println(m.entrySet());
System.out.println( Joiner.on(",").withKeyValueSeparator("").join(m) );

It seems working for small sets of values, without sorting again (Here by keys alphabetically), but is it a reliable way to do? could the order change between the json String and the Map browsing?

Edit: probably LinkedHashMap is more order preserving?

Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
  • 1
    Where exactly is a HashMap being used? – Thilo Jun 11 '12 at 04:52
  • good point, just the Map interface, So the order should never differ from the input String? –  Jun 11 '12 at 05:05
  • Be aware that `LinkedHashMap` doesn't change the order if you re-insert keys (i.e. call `put(k,v)` when `containsKey(k)` returns true). That may or may not be the behaviour you desire! – vaughandroid Jun 11 '12 at 08:42
  • LinkedHashMap doesn't overwrite? –  Jun 11 '12 at 09:12

3 Answers3

3

LinkedHashMap maintains insertion-order. Beyond that there are various SortedMap implementations such as TreeMap.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
1

From this chart, you can see different behaviors among the various implementations of Map bundled with Java 11. Note the "iteration order" column.

Table of map implementations in Java 11, comparing their features

If you want the map to maintain an order based on sorting by the value of the keys, use an implementation that implements SortedMap, or its successor, NavigableMap. That means either TreeMap, or if you need concurrency, ConcurrentSkipListMap.

If you want to maintain the original insertion order, use LinkedHashMap.

If you have enum objects as key, use EnumMap to maintain the keys in order that the enum was defined.

All the other Map implementations bundled with Java 11 make no promises about order of the keys, so avoid them. You may also consider using 3rd-party implementations of Map such as those found in Google Guava library.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

You can check out this question on SO: How does Java order items in a HashMap or a HashTable?

May give you a clearer picture...

Community
  • 1
  • 1
ria
  • 7,904
  • 11
  • 39
  • 46