First thing to do in HashMap?

So, I created a hash map, but I need to get the first key that I entered. This is the code I'm using:

At first:

public static Map<String, Inventory> banks = new HashMap<String, Inventory>(); 

Secondly:

 for(int i = 0; i < banks.size(); i++) { InventoryManager.saveToYaml(banks.get(i), size, //GET HERE); } 

Where he says // Get HERE, I want to get a String from hasmap. Thanks for the help.

+7
java hashmap
source share
2 answers

HashMap does not support key insertion order.

LinkedHashMap should be used because it provides a predictable iteration order, which is usually the order in which keys were inserted into the map (insertion order).

You can use the MapEntry method to iterate over the LinkedHashMap link. So here is what you need to do in the code. First, change the bank card from HashMap to LinkedHashMap:

 public static Map<String, Inventory> banks = new LinkedHashMap<String, Inventory>(); 

And then just repeat it like this:

 for (Map.Entry<String, Inventory> entry : banks.entrySet()) { InventoryManager.saveToYaml(entry.getValue(), size, entry.getKey()); } 

If you only need the first LinkedHashMap element, you can do this:

 banks.entrySet().iterator().next(); 
+14
source share

Answering the question in the header: to get the first key that was inserted, do the following:

 public static Map<String, Inventory> banks = new LinkedHashMap<String, Inventory>(); String firstKey = banks.keySet().iterator().next(); 

Note that you must use LinkedHashMap to maintain the same insertion order when iterating over the map. To iterate over each of the keys in order, starting from the first, do this (and I believe that this is what you intended):

 for (Map.Entry<String, Inventory> entry : banks.entrySet()) { InventoryManager.saveToYaml(entry.getValue(), size, entry.getKey()); } 
+6
source share

All Articles