Java 获取 HashMap 中的第一件事?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18167784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting first the first thing in HashMap?
提问by NineNine
So i've created an hashmap, but i need to get the first key that i entered. This is the code i'm using:
所以我创建了一个哈希图,但我需要获取我输入的第一个键。这是我正在使用的代码:
First:
第一的:
public static Map<String, Inventory> banks = new HashMap<String, Inventory>();
Second:
第二:
for(int i = 0; i < banks.size(); i++) {
InventoryManager.saveToYaml(banks.get(i), size, //GET HERE);
}
Where it says //GET HERE i want to get the String from the hasmap. Thanks for help.
它说 //GET HERE 我想从 hasmap 获取字符串。感谢帮助。
采纳答案by Juned Ahsan
HashMapdoes not manatain the order of insertion of keys.
HashMap不管理键的插入顺序。
LinkedHashMapshould be used as it provides predictable iteration order which is normally the order in which keys were inserted into the map (insertion-order).
应该使用LinkedHashMap,因为它提供了可预测的迭代顺序,这通常是将键插入到映射中的顺序(插入顺序)。
You can use the MapEntry method to iterate over your the LinkedHashMap. So here is what you need to do in your code. First change your banks map from HashMap to the LinkedHashMap:
您可以使用 MapEntry 方法迭代 LinkedHashMap。所以这是您需要在代码中执行的操作。首先将您的银行映射从 HashMap 更改为 LinkedHashMap:
public static Map<String, Inventory> banks = new LinkedHashMap<String, Inventory>();
And then simply iterate it like this:
然后像这样简单地迭代它:
for (Map.Entry<String, Inventory> entry : banks.entrySet()) {
InventoryManager.saveToYaml(entry.getValue(), size, entry.getKey());
}
If you just need the first element of the LinkedHashMap then you can do this:
如果您只需要 LinkedHashMap 的第一个元素,那么您可以这样做:
banks.entrySet().iterator().next();
回答by óscar López
Answering the question in the title: to get the first key that was inserted, do this:
回答标题中的问题:要获取插入的第一个密钥,请执行以下操作:
public static Map<String, Inventory> banks
= new LinkedHashMap<String, Inventory>();
String firstKey = banks.keySet().iterator().next();
Notice that you must use a LinkedHashMap
to preserve the same insertion order when iterating over a map. To iterate over each of the keys in order, starting with the first, do this (and I believe this is what you intended):
请注意,LinkedHashMap
在迭代地图时,您必须使用 a来保留相同的插入顺序。要按顺序迭代每个键,从第一个开始,请执行以下操作(我相信这就是您的意图):
for (Map.Entry<String, Inventory> entry : banks.entrySet()) {
InventoryManager.saveToYaml(entry.getValue(), size, entry.getKey());
}