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
addreturns false instead of storing a duplicate.containsis the question a set exists to answer.- A
TreeSetkeeps itself sorted;firstandlastare the range.
Keywords and builtins used here
newvar
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.
Step 4 of 4 in Collections, step 14 of 29 in Language basics.