Avatar ·

How to properly iterate over all elements of a HashMap in Java? Iterating over a Map

Hello everyone! I'm a beginner in Java, and I have a problem with iterating over a HashMap. I have a map that stores student names and their grades:\n\n```java\nHashMap grades = new HashMap<>();\ngrades.put("Ivan", 85);\ngrades.put("Maria", 92);\ngrades.put("Petr", 78);\n```\n\nI want to display all students and their grades. I tried using a regular for-each loop, but it doesn't work. I wrote it like this:\n\n```java\nfor (String student : grades) {\n System.out.println(student + " - " + grades.get(student));\n}\n```\n\nThe compiler complains: "for-each not applicable to expression type". I understand I'm doing something wrong, but I can't figure out what exactly. I've seen many different options online: some use entrySet(), some use keySet(), and some even use iterators.