typestar

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

  1. put writes; getOrDefault reads without risking null.
  2. merge with Integer::sum is the idiomatic counter.
  3. forEach takes the pair straight into a lambda.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 4 in Collections, step 13 of 29 in Language basics.

← Previous Next →

Maps in other languages