Getting first the first thing in HashMap?

28,730

Solution 1

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();

Solution 2

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());
}
Share:
28,730
NineNine
Author by

NineNine

Updated on July 09, 2022

Comments

  • NineNine
    NineNine almost 2 years

    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.

  • Bohemian
    Bohemian almost 11 years
    This doesn't answer the question.
  • Juned Ahsan
    Juned Ahsan almost 11 years
    @Bohemian Updated the answer with more details.
  • Óscar López
    Óscar López almost 11 years
    Hmmm, you just copied my answer. The least you could do is give me credit...
  • Juned Ahsan
    Juned Ahsan almost 11 years
    @ÓscarLópez It is not copied but the same syntax and using the same variable names as in the questionner code. But still you should find some difference. You already have my vote :-)