Java · Module 8 · Lesson 21 min read

Sets, Maps & Sorting

Set — no duplicates

TypeOrder
HashSetno guaranteed order (fastest)
LinkedHashSetinsertion order
TreeSetsorted
Java
Set<String> tags = new HashSet<>();
tags.add("java"); tags.add("java");   // second add ignored
tags.size();                           // 1

Map — key → value

TypeKey order
HashMapno guaranteed order
LinkedHashMapinsertion order
TreeMapsorted by key
Java
Map<String, Integer> xp = new HashMap<>();
xp.put("Ana", 120);
xp.get("Ana");                  // 120
xp.getOrDefault("Ben", 0);      // 0 (key missing)
xp.containsKey("Ana");          // true
xp.merge("Ana", 10, Integer::sum);  // add 10 → 130

for (Map.Entry<String, Integer> e : xp.entrySet()) {
    System.out.println(e.getKey() + " → " + e.getValue());
}

Keys are unique. Putting an existing key replaces its value.

Queues

  • ArrayDeque → fast stack (push/pop) and queue (offer/poll).
  • PriorityQueue → always hands you the smallest (or highest-priority) item first.

Sorting

  • Comparable = the natural order, defined inside the class with compareTo.
  • Comparator = any custom order, defined outside:
Java
players.sort(Comparator.comparing(Player::score).reversed()
                       .thenComparing(Player::name));

Also handy: Collections.sort(list), Collections.reverse(list), Collections.max(list).

equals & hashCode ⚠️

If you put your own objects in a HashSet or use them as HashMap keys, override both equals() and hashCode(). Records do this for you.

Example

Java
import java.util.*;

public class WordCount {
    public static void main(String[] args) {
        String text = "java is fun and java is fast";
        Map<String, Integer> counts = new TreeMap<>();   // sorted keys

        for (String word : text.split(" ")) {
            counts.merge(word, 1, Integer::sum);
        }
        System.out.println(counts);
        // {and=1, fast=1, fun=1, is=2, java=2}

        Set<String> unique = new LinkedHashSet<>(Arrays.asList(text.split(" ")));
        System.out.println(unique);
        // [java, is, fun, and, fast]
    }
}