The small additions that stuck

Java 8 Course · lesson 13 of 16 · 3 min read

Base64, StringJoiner, Map defaults and parallelSort - unglamorous but used every day.

Open this lesson in the learning hub

Key points

  • Base64 finally arrived in the JDK; before 8 everyone shipped Apache Commons or a copied class.
  • StringJoiner handles the delimiter, prefix, suffix and the empty case you always get wrong.
  • Map.getOrDefault, putIfAbsent, computeIfAbsent and merge removed a decade of null checks.
  • Arrays.parallelSort uses fork/join for large arrays with no code change.
  • Comparator.comparing(...).thenComparing(...) replaced hand-written comparison chains.

Example

import java.util.*;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) {
        String enc = Base64.getEncoder().encodeToString("java 8".getBytes(StandardCharsets.UTF_8));
        System.out.println("Base64      : " + enc + " -> " +
            new String(Base64.getDecoder().decode(enc), StandardCharsets.UTF_8));

        StringJoiner sj = new StringJoiner(", ", "[", "]");
        sj.setEmptyValue("(nothing)");
        sj.add("a").add("b").add("c");
        System.out.println("StringJoiner: " + sj);

        Map<String, Integer> counts = new HashMap<>();
        for (String w : List.of("a", "b", "a", "c", "a")) {
            counts.merge(w, 1, Integer::sum);
        }
        System.out.println("merge       : " + counts);
        System.out.println("getOrDefault: " + counts.getOrDefault("zz", 0));

        int[] nums = { 9, 3, 7, 1, 8 };
        Arrays.parallelSort(nums);
        System.out.println("parallelSort: " + Arrays.toString(nums));
    }
}

The headline features got the attention, but Map.merge and StringJoiner changed daily code just as much.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Java 8 Course course, and every lesson in it is listed on the Java 8 Course contents page.