9

For example, I can loop an ArrayList like this

for (String temp : arraylist)

Can I loop a HashMap by using the similar method?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
SwordW
  • 592
  • 2
  • 6
  • 20

6 Answers6

18

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
8

You can't directly loop a Map like that in Java.

You can, however, loop the keys:

for (SomeKeyObject key : map.keySet())

The values:

for (SomeValueObject value : map.values())

Or even its entries:

for (Map.Entry<SomeKeyObject, SomeValueObject> entry : map.entrySet())
Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

you can do

for (String key : hashmap.keySet()) {
    String value = hashmap.get(key);
}
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
1

You can do it by using an Iterator http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html.

    HashMap<String, String> yourHashMap = new HashMap<>();
    Iterator<Map.Entry<String, String>> it = yourHashMap.entrySet().iterator();
    while(it.hasNext()){
        it.next();
        System.out.println(yourHashMap.get(it));
    }

At first sight it might be tempting to use a for-loop instead of an Iterator, but

you will need an Iterator if you want to modify the elements in your HashMap while iterating over them!

When using a for-loop you cannot remove elements from your map while

 it.remove()

would work well in the above example.

Tim Hallyburton
  • 2,741
  • 1
  • 21
  • 29
1

Use this

map.forEach((k, v) -> System.out.printf("%s %s%n", k, v));
Rahul Jangra
  • 949
  • 6
  • 5
0
public class IterableHashMap<T,U> extends HashMap implements Iterable
    {

        @Override
        public Iterator iterator() {
            // TODO Auto-generated method stub

            return this.keySet().iterator();
        }



    }



    public static void main(String[] args) {

        testA a=new testA();
        IterableHashMap test=a.new IterableHashMap<Object,Object>();
        for(Object o:test)
        {

        }
    }
huseyin tugrul buyukisik
  • 11,469
  • 4
  • 45
  • 97