Maps in Java
Key to value, with safe reads and one-line tallies.
import java.util.HashMap;
var ages = new HashMap<String, Integer>();
ages.put("Ada", 36);
ages.put("Grace", 45);
ages.put("Alan", 41);
// getOrDefault avoids the null a missing key returns
System.out.println(ages.getOrDefault("Grace", 0));
System.out.println(ages.getOrDefault("Kurt", -1));
// merge is the one-line tally
ages.merge("Ada", 1, Integer::sum);
ages.forEach((name, age) -> System.out.println(name + ": " + age));
How it works
putwrites;getOrDefaultreads without risking null.mergewithInteger::sumis the idiomatic counter.forEachtakes the pair straight into a lambda.
Keywords and builtins used here
newvar
The run, in numbers
- Lines
- 14
- Characters to type
- 428
- Tokens
- 131
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 87 seconds.
Step 3 of 4 in Collections, step 13 of 29 in Language basics.