Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java HashMap put in an enhanced for loop just like an ArrayList

For example, I can loop an ArrayList like this

for (String temp : arraylist)

Can I loop a HashMap by using the similar method?

like image 379
SwordW Avatar asked Jan 09 '15 19:01

SwordW


People also ask

Can you use an enhanced for loop on an ArrayList?

The enhanced for loop (sometimes called a "for each" loop) can be used with any class that implements the Iterable interface, such as ArrayList .

Can we iterate HashMap using for loop in Java?

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.

When should a HashMap be used instead of an ArrayList?

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.

Can enhanced for loop iterate over map?

An enhanced for loop can iterate over a Map.


1 Answers

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.

like image 112
Eran Avatar answered Sep 19 '22 18:09

Eran