Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - get index of key in HashMap?

In java if I am looping over the keySet() of a HashMap, how do I (inside the loop), get the numerical index of that key?

Basically, as I loop through the map, I want to be able to get 0,1,2...I figure this would be cleaner than declaring an int and incrementing with each iteration.

Thanks.

like image 226
llm Avatar asked Apr 21 '10 19:04

llm


People also ask

Can we get index in HashMap in Java?

You can't - a set is unordered, so there's no index provided.

Does HashMap have an index?

Arrays store items in an ordered collection and are accessed using an index number (which is an integer). HashMap stores items as key/value pairs. Values can be accessed by indexes, known as keys, of a user-defined type.

How do I find the index of a LinkedHashMap?

Method 1(Using keys array): You can convert all the keys of LinkedHashMap to a set using Keyset method and then convert the set to an array by using toArray method now using array index access the key and get the value from LinkedHashMap. Parameters: The method does not take any parameters.

How to get value of a hashmap key by Index?

You can get key by index. Then get value by key. val item = HashMap<String, String> () // Dummy HashMap. val keyByIndex = item.keys.elementAt (0) // Get key by index. I selected "0". val valueOfElement = item.getValue (keyByIndex) // Get value.

What is the use of HashMap get in Java?

HashMap get () Method in Java. The java.util.HashMap.get () method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

How to get the index of a LinkedHashMap in Java?

You can get all the keys from the LinkedHashMap using the keySet method, convert key set to an ArrayList and then use the indexOf method of the ArrayList class to find the index. 1 2 3

What is the difference between a HashMap and a string?

A HashMap however, store items in " key / value " pairs, and you can access them by an index of another type (e.g. a String ). One object is used as a key (index) to another object (value).


2 Answers

Use LinkedHashMap instead of HashMap It will always return keys in same order (as insertion) when calling keySet()

For more detail, see Class LinkedHashMap

like image 73
trayzey Avatar answered Sep 22 '22 10:09

trayzey


Not sure if this is any "cleaner", but:

List keys = new ArrayList(map.keySet()); for (int i = 0; i < keys.size(); i++) {     Object obj = keys.get(i);     // do stuff here } 
like image 36
Binil Thomas Avatar answered Sep 25 '22 10:09

Binil Thomas