How to efficiently iterate over all entries in a Java Map and get key and value?
Hello everyone! I just started learning Java and encountered a problem.\n\nI have a HashMap where I add some data. For example, I store student names and their grades:\n\n```java\nMap studentGrades = new HashMap<>();\nstudentGrades.put("Anna", 90);\nstudentGrades.put("Ivan", 85);\nstudentGrades.put("Maria", 95);\n```\n\nNow I need to print all students and their grades to the screen. It seems like a simple task, but I see many different ways to iterate over a Map online: via entrySet(), keySet(), values(), lambdas, for-each, iterators... I'm confused.\n\nI tried this:\n\n```java\nfor (String key : studentGrades.keySet()) {\n System.out.println("Student: " + key + ", Grade: " + studentGrades.get(key));\n}\n```\n\nThis works, but I was told it's not efficient
No answers yet.
Log in to leave an answer
Blogs
Generics in Swift: Why They Are Needed and How to Use Them