Skip to content
thesarfo

Concept

HashMaps

Key-value pairs in Java with HashMap — put, get, remove, and iterating with forEach.

views 0

Hashmaps are key-value pairs, equivalent to dictionaries in Python. To use a hashmap, import it from java.util.HashMap, then declare it with the HashMap keyword, angle brackets containing the datatype of the key and value, the name of your hashmap, and assign it to a new HashMap object with matching angle brackets.

import java.util.HashMap;
class Main {
public static void main(String[] args) {
HashMap<String, Integer> examScores = new HashMap<String, Integer>();
examScores.put("Math", 75); // put something into a hashmap
examScores.put("English", 86);
examScores.put("Psychology", 100);
examScores.putIfAbsent("Science", 66); // add Science, since it doesn't exist in our hashmap
examScores.replace("English", 70); // updates the value of the English key
examScores.clear(); // clear the hashmap
examScores.remove("Math"); // removes the key-value pair for Math
System.out.println(examScores.toString()); // print out a hashmap
System.out.println(examScores.get("English")); // print out the value for a single key
System.out.println(examScores.getOrDefault("Religion", -1)); // return the value of the Religion key, else -1 if it doesn't exist
System.out.println(examScores.size()); // prints the length of the examScores hashmap
System.out.println(examScores.containsKey("Math")); // returns true if the key exists
System.out.println(examScores.containsValue(100)); // returns true if the value exists
System.out.println(examScores.isEmpty()); // returns true if the hashmap is empty
}
}

Looping through a hashmap with forEach

class Main {
public static void main(String[] args) {
HashMap<String, Integer> examScores = new HashMap<String, Integer>();
examScores.put("Math", 75);
examScores.put("English", 86);
examScores.put("Psychology", 100);
examScores.forEach((subject, score) -> {
System.out.println(subject + "-" + score);
examScores.replace(subject, score - 10);
});
System.out.println(examScores.toString());
}
}

Note that the forEach method for a hashmap takes the key and the value as arguments.