Collections in Java: HashMap, HashSet and TreeMap

Lesson 15 of 16 · Java

A map (dictionary) stores key → value pairs and lets you find a value by its key quickly. A set stores elements without repetition. These are the structures used most often for counting, grouping and checking "have we already seen this".

Before you start: what you need to know first – lists, strings.
How to learn: type in and run each example, and try to solve the tasks at the end on your own first; open the hint and the solution only after that. All the programs are in Java (Java 17 or newer); each one has been compiled and run and gives the output shown.

HashMap: key and value

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> population = new HashMap<>();
        population.put("Belgrade", 1_681_405);   // adding a pair
        population.put("Novi Sad", 368_967);
        population.put("Nis", 249_501);
        population.put("Nis", 249_816);          // the same key: the value is replaced

        System.out.println(population.get("Novi Sad"));
        System.out.println(population.get("Kragujevac"));          // no such key: null
        System.out.println(population.getOrDefault("Kragujevac", 0));
        System.out.println("Has Nis? " + population.containsKey("Nis") + ", pairs: " + population.size());

        population.remove("Belgrade");
        // printing alphabetically by key: a copy in a TreeMap (a HashMap has no particular order)
        for (Map.Entry<String, Integer> e : new TreeMap<>(population).entrySet())
            System.out.println(e.getKey() + " -> " + e.getValue());
    }
}

Output:

368967
null
0
Has Nis? true, pairs: 3
Nis -> 249816
Novi Sad -> 368967

A HashMap does not keep any particular order of keys. If you need a sorted order, use a TreeMap, and if you need the order of adding – a LinkedHashMap.

Counting occurrences

The most common use of a map: how many times each element appeared. The method merge(key, 1, Integer::sum) adds 1 to the existing value or sets 1 for a new key.

import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String text = sc.nextLine().toLowerCase();
        Map<String, Integer> count = new TreeMap<>();     // keys in alphabetical order
        for (String word : text.split("[^a-z]+")) {
            if (word.isEmpty()) continue;
            count.merge(word, 1, Integer::sum);           // the same as: count.put(word, count.getOrDefault(word, 0) + 1)
        }
        System.out.println(count);

        // the most common word
        String mostCommon = null;
        for (String w : count.keySet())
            if (mostCommon == null || count.get(w) > count.get(mostCommon))
                mostCommon = w;
        System.out.println("Most common: " + mostCommon + " (" + count.get(mostCommon) + ")");
    }
}

Input: Ana has a cat. The cat has milk, and Ana has a dog too.

Output:

{a=2, ana=2, and=1, cat=2, dog=1, has=3, milk=1, the=1, too=1}
Most common: has (3)

HashSet and TreeSet: a set without repetition

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        Set<Integer> a = new TreeSet<>(List.of(5, 1, 3, 9, 7, 3, 1));   // duplicates disappear, sorted
        Set<Integer> b = new TreeSet<>(List.of(3, 4, 5, 6));
        System.out.println("a = " + a + ", b = " + b);

        Set<Integer> intersection = new TreeSet<>(a);
        intersection.retainAll(b);                  // keep only the common ones
        Set<Integer> union = new TreeSet<>(a);
        union.addAll(b);
        Set<Integer> difference = new TreeSet<>(a);
        difference.removeAll(b);
        System.out.println("intersection " + intersection + ", union " + union + ", a\\b " + difference);

        // add returns false if the element already exists – the first repetition in an array
        Set<String> seen = new HashSet<>();
        for (String s : new String[]{"red", "blue", "yellow", "blue", "red"})
            if (!seen.add(s)) {
                System.out.println("First repetition: " + s);
                break;
            }
    }
}

Output:

a = [1, 3, 5, 7, 9], b = [3, 4, 5, 6]
intersection [3, 5], union [1, 3, 4, 5, 6, 7, 9], a\b [1, 7, 9]
First repetition: blue

The contains check in a HashSet and a HashMap is practically instant, no matter how many elements there are, while a list has to look at the elements one by one.

TreeMap: sorted keys and searching

import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        // points threshold -> grade
        TreeMap<Integer, Integer> scale = new TreeMap<>();
        scale.put(0, 1);
        scale.put(50, 2);
        scale.put(65, 3);
        scale.put(80, 4);
        scale.put(90, 5);

        int[] points = {45, 50, 72, 89, 100};
        for (int p : points) {
            // floorKey: the largest key that is <= p
            int grade = scale.get(scale.floorKey(p));
            System.out.println(p + " points -> grade " + grade);
        }
        System.out.println("first threshold " + scale.firstKey() + ", last " + scale.lastKey());
    }
}

Output:

45 points -> grade 1
50 points -> grade 2
72 points -> grade 3
89 points -> grade 4
100 points -> grade 5
first threshold 0, last 90
StructureOrderWhen to use it
HashMap / HashSetno particular orderthe fastest; when the order does not matter
LinkedHashMap / LinkedHashSetthe order of addingwhen the order has to be remembered
TreeMap / TreeSetsortedsorted output, floorKey, ceilingKey

A map with a list: grouping

A value in a map can also be a list. The computeIfAbsent method creates an empty list when a key appears for the first time:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        Map<String, List<String>> byClass = new TreeMap<>();
        for (int i = 0; i < n; i++) {
            String name = sc.next(), schoolClass = sc.next();
            byClass.computeIfAbsent(schoolClass, k -> new ArrayList<>()).add(name);
        }
        for (var e : byClass.entrySet())              // var: the compiler works out the type
            System.out.println(e.getKey() + ": " + String.join(", ", e.getValue()));
    }
}

Input: 5 Ana 7a Mark 8b Iva 7a Luke 8b Sara 7a

Output:

7a: Ana, Iva, Sara
8b: Mark, Luke

Practice tasks

Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.

TASK 01Difficulty: medium

Anagrams

Two words are anagrams if they have the same letters in a different order (cat and act). Read n, then n words made of lower-case letters. Print the groups of anagrams (only groups with at least two words), each on its own line, the words inside a group in alphabetical order, and the groups in alphabetical order by their first word.

Example

Input

7
top
listen
cat
pot
silent
act
enlist

Output

act cat
enlist listen silent
pot top
TASK 02Difficulty: medium

Two numbers with a given sum

Read n and k, then n whole numbers (n ≤ 200 000). Print the number of pairs of positions i < j for which a[i] + a[j] = k. A solution with two loops is too slow – one pass is needed.

Example 1

Input

6 7
1 6 3 4 5 2

Output

3

Example 2

Input

5 4
2 2 2 1 3

Output

4
Common mistakes and tips
  • get for a key that does not exist returns null; if you convert the value to an int, this causes a NullPointerException. Use getOrDefault.
  • Do not rely on the order in which a HashMap is printed – for sorted output use a TreeMap.
  • A key in a map and an element of a set must not be changed while they are in the collection (especially with your own classes).
  • For your own class as a key, the methods equals and hashCode must exist; a record has them automatically.

Check your knowledge

Open the quiz

Maps and sets

1. What happens when put is called with a key that already exists?




2. Which structure keeps its keys sorted?




3. What does set.add(x) return if x already exists in the set?




4. What is a map best suited for?