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.
You can't - a set is unordered, so there's no index provided.
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.
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.
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.
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.
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
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).
Use LinkedHashMap instead of HashMap It will always return keys in same order (as insertion) when calling keySet()
For more detail, see Class LinkedHashMap
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With