×

java · level 2 · unit 2 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A keeps each value once and ignores duplicates.

A HashSet is a bag that refuses a . .add("red") puts red in. Add red again and nothing changes: .add gives back false to say it was already there.

Sets are fast at one question: is this in here? .contains answers it, and .size() counts the different values. A HashSet has no index and no order, so reach for a when you want the values sorted.

To clean the repeats out of a list, pour it into a set: new TreeSet<>(stamps).

import java.util.*;
public class Main {
    public static void main(String[] args) {
        HashSet<String> colours = new HashSet<>();
        System.out.println(colours.add("red"));
        System.out.println(colours.add("blue"));
        System.out.println(colours.add("red"));
        System.out.println(colours.size() + " " + colours.contains("blue"));
        List<String> stamps = List.of("UK", "France", "UK", "Spain", "France");
        System.out.println(new TreeSet<>(stamps));
    }
}

Use a list when order or repeats matter, and a set when they do not.