Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialKishan Gupta
6,567 Pointsfor-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
Kyle McCullen
16,639 PointsThe 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.
Tonnie Fanadez
UX Design Techdegree Graduate 22,796 PointsI also think the second inner for-each loop isn't necessary since you can simple print the keys alongside the values.
Kishan Gupta
6,567 PointsKishan Gupta
6,567 PointsIt worked thanks :)