I have following LinkedHashMap declaration.
LinkedHashMap<String, ArrayList<String>> test1
my point is how can i iterate through this hash map. I want to do this following, for each key get the corresponding arraylist and print the values of the arraylist one by one against the key.
I tried this but get only returns string,
String key = iterator.next().toString(); ArrayList<String> value = (ArrayList<String> )test1.get(key)
1. Iterating over Map.entrySet() using For-Each loop : Map.entrySet() method returns a collection-view(Set<Map.Entry<K, V>>) of the mappings contained in this map. So we can iterate over key-value pair using getKey() and getValue() methods of Map.Entry<K, V>.
There are basically two ways to iterate over LinkedHashMap:Using keySet() and get() Method. Using entrySet() and Iterator.
To convert all values of the LinkedHashMap to a List using the values() method. The values() method of the LinkedHashMap class returns a Collection view of all the values contained in the map object. You can then use this collection to convert it to a List object.
Obtain an iterator to the start of the collection by calling the collection's iterator() method. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true. Within the loop, obtain each element by calling next().
for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) { String key = entry.getKey(); ArrayList<String> value = entry.getValue(); // now work with key and value... }
By the way, you should really declare your variables as the interface type instead, such as Map<String, List<String>>
.
I'm assuming you have a typo in your get statement and that it should be test1.get(key). If so, I'm not sure why it is not returning an ArrayList unless you are not putting in the correct type in the map in the first place.
This should work:
// populate the map Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>(); test1.put("key1", new ArrayList<String>()); test1.put("key2", new ArrayList<String>()); // loop over the set using an entry set for( Map.Entry<String,List<String>> entry : test1.entrySet()){ String key = entry.getKey(); List<String>value = entry.getValue(); // ... }
or you can use
// second alternative - loop over the keys and get the value per key for( String key : test1.keySet() ){ List<String>value = test1.get(key); // ... }
You should use the interface names when declaring your vars (and in your generic params) unless you have a very specific reason why you are defining using the implementation.
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