Lesson 38
HashMap and HashSet
HashMap stores key-value pairs. HashSet stores unique values only.
Java Track
Save progress as you learn.
61 lessons
Lesson content
HashMap: key-value pairs. HashSet: unique values only.
Key Terms
- HashMap: Stores data as key-value pairs.
- HashSet: Stores unique elements, no duplicates.
- Key: Unique identifier in a HashMap.
- Hashing: Converts data to hash code for storage.
Example: HashMap
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<Integer, String> students = new HashMap<>();
students.put(101, "John");
students.put(102, "Alice");
students.put(103, "David");
System.out.println(students);
System.out.println("Student: " + students.get(102));
}
}{101=John, 102=Alice, 103=David}
Student: AliceHashMap Methods
map.put(101, "John"); // add
map.get(101); // retrieve
map.remove(101); // delete
map.containsKey(101); // check key
map.containsValue("John"); // check value
map.size(); // countExample: HashSet
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple");
fruits.add("Mango");
System.out.println(fruits);
}
}[Apple, Banana, Mango]HashSet Methods
set.add("Java"); // add
set.remove("Java"); // remove
set.contains("Java"); // check
set.size(); // count
set.clear(); // clear allIterating HashMap
for (HashMap.Entry<Integer, String> entry : students.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}Iterating HashSet
for (String fruit : fruits) {
System.out.println(fruit);
}FAQ
1. HashMap vs HashSet?
HashMap: key-value. HashSet: unique values only.
2. HashSet allow duplicates?
No. Auto-removed.
3. HashMap duplicate values?
Yes. Values can repeat. Keys cannot.
HashMap stores key-value pairs.
HashSet stores unique values only.
Keys in HashMap must be unique.
HashSet backed by HashMap internally.
Neither maintains insertion order.
HashMap allows one null key.
HashSet allows one null value.
Where Java is used
Java in real-world development
HashMap
Key-value pairs. Fast lookup by key. One null key allowed.
HashSet
Unique values only. Duplicates auto-removed. One null allowed.
HashMap Methods
put(), get(), remove(), containsKey(), containsValue(), size()
HashSet Methods
add(), remove(), contains(), size(), clear()
Use HashMap When
Data has key-value relationships. Fast key-based retrieval needed.
Use HashSet When
Unique values required. Duplicate prevention needed.