For each


how do for-loops with ‘:’ work and in what case is it required to use ‘.keySet()’?

Earlier in the course i had to use something like

for (String grade : grades.keySet()) {}

but just know i had an error that i was only able to fix by watching the attached video.
The suggested solution in this example doesn’t use ‘.keySet()’.

for (Integer grade : grades) {}

is the datatype the decisive factor for when ‘.keySet()’ is required?


the for loop consist of two parts. On the left the variable which java will assign the values to, on the right what you want to loop over:

for (Integer grade : grades) {

will print each grade of the grades array/arraylist

keySet is a method for hashmap:


Okay that’s good to know. But apparently i still don’t know how to make the for loops work.
Would you mind to look at this?

public void getFinishedBooks(HashMap<String, Boolean> library) {

     for (String book : library.setKey()) {
        //if ()


can have the exercise url? Then i can actually run the code, that is a lot easier for debugging

and your whole code, maybe the mistake is not even within this method


Sure, it’s:

import java.util.HashMap;

// Hey, this is library!
public class Library {
  public Library() {}
  public void getFinishedBooks(HashMap<String, Boolean> library) {
    if (library.size() < 1) {
      System.out.println("Error! The hashmap 'library' is empty.");
    }	else {
      for (HashMap<String> book : library.setKey()) {
        // if () 


setKey? You mean keySet(), quite a differences there

the keySet() method gives you the keys of hasmhap, which are strings, so book should be of type string

and there is no main method in your code? Every java program needs a main method


Thank you very much! No more errors :slight_smile:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.