Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first the first thing in HashMap? [duplicate]

Tags:

java

hashmap

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.

like image 464
NineNine Avatar asked Aug 11 '13 01:08

NineNine


1 Answers

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();
like image 57
Juned Ahsan Avatar answered Oct 02 '22 14:10

Juned Ahsan