Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is for each on a map with EL possible?

 
Jonny Andersson
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to learn the EL for the J2EE SCWCD-exam and have trouble when I try to loop over a map with a for each that use EL. Here is an example of what I try to accomplish, is it possible to do this?

I have a servlet that creates a map like this one:


It contains movie objects that has a name property like this:


And I the forward to a JSP page to print the list of movies using a for each like this:



But it does not work. I get some error that say that a TreeMap$entry not have an attribute name ...

You can see what I try to do, is it possible or do you have a better, working, example?

And just to understand, is not



a reference to a movie objekt? One thing that complicates here is of course that I have a map. A map have keys and objects, am I iterating over the keys or the objects? With a list would I know that it is the objects, but I am not quite sure with a map. In normal Java would I have to iterate over the keys and then get the objects from the map using that keys.
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using the forEach loop for a Map will return an instance of Map.Entry for each iteration. If you look at the Map.Entry class, you'll see that it has a key and a value. So in your example, you should do the following :
 
Jonny Andersson
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That example from you looks so reasonable so that I already know that it must be correct ... I will try it later when I have time to look at it again. A lot of thanks for your help!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic