For example, I can loop an ArrayList
like this
for (String temp : arraylist)
Can I loop a HashMap by using the similar method?
The enhanced for loop (sometimes called a "for each" loop) can be used with any class that implements the Iterable interface, such as ArrayList .
Method 1: Using a for loop to iterate through a HashMap. Iterating a HashMap through a for loop to use getValue() and getKey() functions. Implementation: In the code given below, entrySet() is used to return a set view of mapped elements. From the code given below: set.
While HashMap stores elements with key and value pairs that means two objects. So HashMap takes more memory comparatively. ArrayList allows duplicate elements while HashMap doesn't allow duplicate keys but does allow duplicate values.
An enhanced for loop can iterate over a Map.
You can iterate over the keys, entries or values.
for (String key : map.keySet()) {
String value = map.get(key);
}
for (String value : map.values()) {
}
for (Map.Entry<String,String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
This is assuming your map has String keys and String values.
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