简体   繁体   English

HashMap,其中键的顺序很重要

[英]HashMap where the order of keys is important

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我使用 HashMaps 来存储对的集合,但我还必须确保从第一个 json 序列化(来自 Php 客户端)到 Java HashMap 集合浏览,键的顺序将是相同的

//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? json String 和 Map 浏览之间的顺序可以改变吗?

Edit : probably LinkedHashMap is more order preserving?编辑:可能 LinkedHashMap 更能保留顺序?

LinkedHashMap maintains insertion-order. LinkedHashMap维护插入顺序。 Beyond that there are various SortedMap implementations such as TreeMap .除此之外,还有各种SortedMap实现,例如TreeMap

You can check out this question on SO: How does Java order items in a HashMap or a HashTable?您可以在 SO 上查看这个问题: Java 如何对 HashMap 或 HashTable 中的项目进行排序?

May give you a clearer picture...可以给你更清晰的图...

From this chart, you can see different behaviors among the various implementations of Map bundled with Java 11. Note the "iteration order" column.从该图表中,您可以看到与 Java 11 捆绑在一起的Map的各种实现之间的不同行为。请注意“迭代顺序”列。

Java 11 中的地图实现表,比较它们的特性

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 .如果您希望地图根据键的值进行排序来维护顺序,请使用实现SortedMap或其后继NavigableMap That means either TreeMap , or if you need concurrency, ConcurrentSkipListMap .这意味着TreeMap ,或者如果您需要并发, ConcurrentSkipListMap

If you want to maintain the original insertion order, use LinkedHashMap .如果要保持原始插入顺序,请使用LinkedHashMap

If you have enum objects as key, use EnumMap to maintain the keys in order that the enum was defined.如果您将枚举对象作为键,请使用EnumMap来维护键,以便定义枚举。

All the other Map implementations bundled with Java 11 make no promises about order of the keys, so avoid them.与 Java 11 捆绑在一起的所有其他Map实现都没有承诺键的顺序,因此请避免使用它们。 You may also consider using 3rd-party implementations of Map such as those found in Google Guava library.您还可以考虑使用Map 3rd 方实现,例如在Google Guava库中找到的那些。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM