JV

Java Fundamentals

19 lessons

Progress0%
1. Introduction to Java
1What is Java?
2. Variables and Data Types
1Primitive Types
3. Control Flow
ConditionalsLoops
4. Methods
Defining MethodsMethod Overloading
5. Object-Oriented Programming
Classes and ObjectsInheritanceInterfaces and Abstract Classes
6. Collections
ArrayList and LinkedListHashMap and HashSet
7. Exception Handling
Checked & Unchecked Exceptionstry-with-resources & Custom Exceptions
8. Generics
Generic Classes & MethodsWildcards & Type Erasure
9. Modern Java
Lambdas & Functional InterfacesStream API & Optional
10. File I/O
java.nio.file APIBuffered I/O & try-with-resources
All Tutorials
JavaCollections
Lesson 11 of 19 min
Chapter 6 · Lesson 2

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() and equals().
  • Use LinkedHashMap to maintain insertion order.
  • Use TreeMap for sorted key order.
  • HashSet is backed by a HashMap internally.

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?

PreviousNext