typestar

Sets in Java

Membership in constant time, or sorted for free.

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

var seen = new HashSet<>(Set.of("read", "eval"));
System.out.println(seen.add("print"));   // true: it was new
System.out.println(seen.add("read"));    // false: already there
System.out.println(seen.contains("eval"));

// a TreeSet keeps itself sorted
var sorted = new TreeSet<>(Set.of("web", "api", "cli"));
System.out.println(sorted);
System.out.println(sorted.first() + " .. " + sorted.last());

How it works

  1. add returns false instead of storing a duplicate.
  2. contains is the question a set exists to answer.
  3. A TreeSet keeps itself sorted; first and last are the range.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
473
Tokens
140
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 88 seconds.

Type this snippet

Step 4 of 4 in Collections, step 14 of 29 in Language basics.

← Previous Next →