Start learning free

LESSON 125 OF 671 · DICTIONARIES

Dictionary Length in Java

Lesson

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.

STEP 1 OF 1
    Ctrl + Enter to check