3

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);
      }
    }
  }
}
user743414
  • 936
  • 10
  • 23
Jose C.
  • 33
  • 1
  • 7
  • Note also that the iteration order of `HashMap` isn't consistent. If you want to keep the insertion order while iterating, use `LinkedHashMap`. If you want alphabetic ordering by book title, use `TreeMap`. – Mick Mnemonic Oct 09 '18 at 11:58

4 Answers4

5

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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • could you also explain why my syntax doesnt work? – Jose C. Oct 16 '18 at 10:29
  • @JoseC. `for(String book : library)` is invalid because `HashMap` is not `Iterable`. That syntax is allowed with arrays and types that implement `Iterable`. `map.entrySet()` returns a `Set`, which is a Collection implementing `Iterable` (just like `List`) – ernest_k Oct 16 '18 at 10:40
2

You have different ways to iterate over a Map

forEach from Java 8 (this is more efficient)

library.forEach((k, v) -> System.out.println(v));

forEach and Entry

for (library.Entry<String, Boolean> pair : library.entrySet()) {
    System.out.println(pair.getValue());
}

forEach and keySet

for (String key : library.keySet()) {
    System.out.println(library.get(key));
}
robertobatts
  • 965
  • 11
  • 22
0

You can use entrySet().

Quote from https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html:

public Set> entrySet() Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

Alexander Agopov
  • 133
  • 4
  • 12
0

You can traverse using below code by java8:

Map<String, Boolean> library= new HashMap<>();
    library.put("Book1",true);
    library.put("Book2",true);
    library.put("Book3",false);
    library.forEach((key, value) -> {
        if(value){
            System.out.println("Book = " + value);
        }
    });
Pankaj Kumar
  • 151
  • 1
  • 3
  • 9