10

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.

NineNine
  • 324
  • 1
  • 2
  • 11

2 Answers2

15

HashMap does not manatain the order of insertion of keys.

LinkedHashMap should be used as it provides predictable iteration order which is normally the order in which keys were inserted into the map (insertion-order).

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:

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:

banks.entrySet().iterator().next();
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
6

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):

for (Map.Entry<String, Inventory> entry : banks.entrySet()) {
    InventoryManager.saveToYaml(entry.getValue(), size, entry.getKey());
}
Óscar López
  • 232,561
  • 37
  • 312
  • 386