HashMap and HashSet
HashMap and HashSet in Java
Map interface
A Map stores key-value pairs. Each key is unique. HashMap is the most common implementation, offering average O(1) put/get.
Common Map operations
put(key, value),get(key),remove(key)containsKey(key),containsValue(value)keySet(),values(),entrySet()getOrDefault(key, defaultValue)
Set interface
A Set stores unique elements. HashSet provides O(1) average add/contains/remove. Order is not guaranteed.
Iterating a Map
java
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}Key points:
- Keys in a HashMap must correctly implement
hashCode()andequals(). - Use
LinkedHashMapto maintain insertion order. - Use
TreeMapfor sorted key order. HashSetis backed by aHashMapinternally.
Code Examples
HashMap operationsjava
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 80);
scores.put("Charlie", 90);
System.out.println("Alice: " + scores.get("Alice"));
System.out.println("Dave: " + scores.getOrDefault("Dave", 0));
System.out.println("Has Bob: " + scores.containsKey("Bob"));
scores.put("Bob", 85); // update
for (Map.Entry<String, Integer> e : scores.entrySet()) {
System.out.println(e.getKey() + " -> " + e.getValue());
}
}
}getOrDefault avoids null returns. Putting a key that already exists overwrites the value. entrySet() iterates all pairs.
HashSet — unique elementsjava
import java.util.HashSet;
import java.util.Set;
public class SetDemo {
public static void main(String[] args) {
Set<String> tags = new HashSet<>();
tags.add("java");
tags.add("programming");
tags.add("java"); // duplicate — ignored
tags.add("oop");
System.out.println("Size: " + tags.size());
System.out.println("Has 'java': " + tags.contains("java"));
// Find duplicates in an array
int[] nums = {1, 2, 3, 2, 4, 3, 5};
Set<Integer> seen = new HashSet<>();
Set<Integer> duplicates = new HashSet<>();
for (int n : nums) {
if (!seen.add(n)) duplicates.add(n);
}
System.out.println("Duplicates: " + duplicates);
}
}add() returns false if the element was already present. HashSet.add() and contains() are O(1) average.
Quick Quiz
1. What does `map.getOrDefault(key, 0)` return when the key is absent?
2. Does a HashSet allow duplicate elements?
Was this lesson helpful?