Java Java Data Structures Exploring the Java Collection Framework Maps

for-each not applicable to expression type

So i am trying to print every Author's treet separately here instead the messy way Craig showed So i used a for-each loop to loop through the map

And then i also tried to loop through that specific Key's value to print every treet separately Since the value of the Map is a List of Treet, when entry.getValue() is called it must return a list of Treet right ? so i can loop through every treets

    Map<String, List<Treet>> treetsByAuthor = new HashMap<String, List<Treet>>();
    for (Treet treet : treets) {
      List<Treet> authoredTreets = treetsByAuthor.get(treet.getAuthor());
      if (authoredTreets == null) {
        authoredTreets = new ArrayList<Treet>();
        treetsByAuthor.put(treet.getAuthor(), authoredTreets);
      }
      authoredTreets.add(treet);
    }

for (Map.Entry entry : treetsByAuthor.entrySet()) {
      System.out.printf("Treets by %s are : \n", entry.getKey());
      for(Treet treet : entry.getValue()) {
        System.out.println(treet);
      }
    }

But instead i am getting this error

Example.java:62: error: for-each not applicable to expression type                                                                                                                    
      for(Treet treet : entry.getValue()) {                                                                                                                                           
                                      ^                                                                                                                                               
  required: array or java.lang.Iterable                                                                                                                                               
  found:    Object                                                                                                                                                                    
1 error

2 Answers

The only thing you need to change is to specify the types of the entry (i.e <String, List<Treet>> in this example)

for (Map.Entry<String, List<Treet>> entry : treetsByAuthor.entrySet()){

I hope this helps.

It worked thanks :)

Tonnie Fanadez
Tonnie Fanadez
UX Design Techdegree Graduate 22,777 Points

I also think the second inner for-each loop isn't necessary since you can simple print the keys alongside the values.