In Java, you can get the number of key-value pairs in a HashMap using the size() method:
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Charlie", 72);
int count = scores.size();
System.out.println(count); // 3
size() returns the number of entries. You can also check if it's empty with isEmpty():
System.out.println(scores.isEmpty()); // false
HashMap<String, Integer> empty = new HashMap<>();
System.out.println(empty.size()); // 0
Assignment
Follow the Coding Tutorial and get the number of entries in scores!
Hint
Use scores.size() and assign it to count.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
