0

Possible Duplicate:
How do I iterate over each Entry in a Map?

I'm following this solution to no effect: https://stackoverflow.com/a/1835742/666468

I am trying to output this Map:

//protected Map<String,String> getImageTagAttributes()
Image image = new Image(resource);
for (Map<String, String> foo : image.getImageTagAttributes()) {
        String key = foo.getKey();
        String value = foo.getValue();

        //output here
    }

But I get this error: Can only iterate over an array or an instance of java.lang.Iterable

I imported java.util.Iterator as well, but no luck.

p.s. I wish I could install and use JSTL, but it's not my call.

Community
  • 1
  • 1
justacoder
  • 2,684
  • 6
  • 47
  • 78
  • 1
    What is returned by `image.getImageTagAttributes()`? A `Map` has a key/value pair mechanism. You need to use an `EntrySet` to iterate over the `Map`. – Lion Jan 31 '13 at 17:36
  • Use the iterator as suggested in the following solution : http://stackoverflow.com/questions/672916/how-to-get-image-height-and-width-using-java – Zafer Jan 31 '13 at 17:37
  • 2
    How did you miss the `entrySet()` method in the answer you found? – BalusC Jan 31 '13 at 17:45
  • @BalusC, I presumed `countries.entrySet()` is unique to the example in question, and not to me specifically. My knowledge in Java is rookie at best. – justacoder Jan 31 '13 at 18:32

3 Answers3

2

Not sure where did you get that Image class, but if image.getImageTagAttributes() returns Map<String, String> then maybe try it this way

Image image = new Image(resource);
Map<String, String> map = image.getImageTagAttributes();
for (Map.Entry<String,String> foo : map.entrySet()) {
    String key = foo.getKey();
    String value = foo.getValue();

    //output here
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

You cannot iterate a Map in for each loop.

Get the map object keyset and then iterate it.

Then inside the for loop try retrieving the value for each key from the map.

user1760178
  • 6,277
  • 5
  • 27
  • 57
0

Because this not the correct way to iterate over a Map :

    Image image = new Image(resource);
    Map<String, String> foo =  image.getImageTagAttributes();
    Set<String> key = foo.keyset(); 
     for ( k : keys ) {
           String value = foo.get(k);
        //output here
    }

or you can interate that way :

    Image image = new Image(resource);
    Map<String, String> foo =  image.getImageTagAttributes();
    Set<Map.Entry<String,String>> entries = foo.entrySet();

    for(Map.Entry<String, String> e : entries){
       String key  = e.getKey();
       String value = e.getValue();
        //output
    }

In my answer, I suppose that image.getImageTagAttributes(); returns a Map<String,String>

Dimitri
  • 8,122
  • 19
  • 71
  • 128