如何保持插入顺序 [英] How to Maintain order of insertion
问题描述
我想将一个键,值对添加到哈希表(或任何其他集合)中,但必须保持插入顺序.我该怎么办?
I want to add a key, value pair into a hashtable (or any other collection) but have to maintain insertion order. How can I do this?
就像我将1作为键"one"添加为值,将2作为键并添加"2"作为值一样.
Like I'll add 1 as key "one" as value, 2 as key and "two" as value.
输出应为:
1:one
2:two
推荐答案
Here are the characteristic differences of some important Map
implementations:
-
LinkedHashMap
:与可预测的迭代顺序,通常是将键插入到映射中的顺序(插入顺序)." -
HashMap
:不保证地图的顺序" -
TreeMap
:是根据其键的自然顺序或Comparator
进行排序"- 即这是
SortedMap
LinkedHashMap
: "with predictable iteration order [...] which is normally the order in which keys were inserted into the map (insertion-order)."HashMap
: "makes no guarantees as to the order of the map"TreeMap
: "is sorted according to the natural ordering of its keys, or by aComparator
"- i.e. it's a
SortedMap
在这种情况下,您似乎需要
LinkedHashMap
.So it looks like
LinkedHashMap
is what you need in this case.以下是说明差异的代码段;它还显示了遍历
Map
的所有条目的常用方法,以及如何使用接口引用对象使实现的选择具有极大的灵活性.Here's a snippet to illustrate the differences; it also shows a common way to iterate over all entries of a
Map
, and how using an interface to refer to objects allow great flexibility of choice of implementation.import java.util.*; public class MapExample { public static void main(String[] args) { populateThenDump(new HashMap<String,Integer>()); populateThenDump(new TreeMap<String,Integer>()); populateThenDump(new LinkedHashMap<String,Integer>()); } static void populateThenDump(Map<String,Integer> map) { System.out.println(map.getClass().getName()); map.put("Zero", 0); map.put("One", 1); map.put("Two", 2); map.put("Three", 3); map.put("Four", 4); for (Map.Entry<String,Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + " => " + entry.getValue()); } } }
以上代码段的输出为(在ideone.com上看到的):
The output of the above snippet is (as seen on ideone.com):
java.util.HashMap // unordered, results may vary Three => 3 Zero => 0 One => 1 Four => 4 Two => 2 java.util.TreeMap // ordered by String keys lexicographically Four => 4 One => 1 Three => 3 Two => 2 Zero => 0 java.util.LinkedHashMap // insertion order Zero => 0 One => 1 Two => 2 Three => 3 Four => 4
相关问题
- 在地图上迭代
- 迭代并从地图中删除
- i.e. it's a
- 即这是