I am trying to use a HashMap to map a unique string to a string ArrayList like this:
HashMap<String, ArrayList<String>>
Basically, I want to be able to access the keys by number, not by using the key's name. And I want to be able to access said key's value, to iterate over it. I'm imagining something like this:
for(all keys in my hashmap) { for(int i=0; i < myhashmap.currentKey.getValue.size(); i++) { // do things with the hashmaps elements } }
Is there an easy way to do this?
HashMap stores items as key/value pairs. Values can be accessed by indexes, known as keys, of a user-defined type.
Use the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object. Convert the entry set to an array using the toArray() method. And get TreeMap key or TreeMap value using index with the help of getKey() and getValue() method.
You can't - a set is unordered, so there's no index provided.
Here is the general solution if you really only want the first key's value
Object firstKey = myHashMap.keySet().toArray()[0]; Object valueForFirstKey = myHashMap.get(firstKey);
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