Jose C. :
I need to iterate each value of a HashMap in my method but it gives me a syntax error at the for each loop
Library.java:12: error: for-each not applicable to expression type for(String book : library){ ^ required: array or java.lang.Iterable found: HashMap
This is the relevant code
public void getFinishedBooks(HashMap<String, Boolean> library)
{
if(library.size()<1)
{
System.out.println("Library is empty!");
}
else
{
for(String book : library)
{
if(library.get(book) ==true)
{
System.out.println(book);
}
}
}
}
ernest_k :
You can iterate over the set of entries:
for (Entry<String, Boolean> book : library.entrySet()) {
if (book.getValue()) {
System.out.println(book.getKey());
}
}
Map.entrySet()
returns a Set
of entries (java.util.Map.Entry
). Each entry contains a pair with a key and its value.