Tech Interview RoomStudy guides

Java 21

Java 21: Migrate a legacy report method from Java 7 to Java 8, 17 and 21, step by step.

Advanced · 2 min read · Lesson 8 of 8 in Java 21

Problem

A legacy method takes raw transactions (Map<String, Object> rows with type, amount and date), keeps the last 30 days, and produces totals per type where REFUND counts as negative and FEE as a fixed charge. Interviewers love "how would you modernise this?" because it tests every version at once. The behaviour must stay identical across versions.

Version 1: Java 7 (the starting point)

Raw maps, casts, Date arithmetic in milliseconds, manual null checks, string comparisons and mutable accumulators.

java
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

class ReportJava7 {
    static Map<String, Long> totals(List<Map<String, Object>> rows, Date today) {
        Map<String, Long> totals = new TreeMap<String, Long>();
        long cutoff = today.getTime() - 30L * 24 * 60 * 60 * 1000;          // DST-unsafe millisecond math
        for (Map<String, Object> row : rows) {
            if (row == null || row.get("date") == null) continue;
            Date d = (Date) row.get("date");
            if (d.getTime() < cutoff) continue;
            String type = (String) row.get("type");
            long amount = ((Number) row.get("amount")).longValue();
            long value;
            if ("REFUND".equals(type)) value = -amount;
            else if ("FEE".equals(type)) value = 25;
            else value = amount;
            Long current = totals.get(type);
            totals.put(type, current == null ? value : current + value);
        }
        return totals;
    }
}

Version 2: Java 8 (streams, java.time, method references)

Typed LocalDate comparisons, a stream pipeline, toMap with a merge function. Rows are still untyped maps.

java
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors;

class ReportJava8 {
    static Map<String, Long> totals(List<Map<String, Object>> rows, LocalDate today) {
        LocalDate cutoff = today.minusDays(30);
        return rows.stream()
            .filter(Objects::nonNull)
            .filter(r -> r.get("date") instanceof LocalDate)
            .filter(r -> !((LocalDate) r.get("date")).isBefore(cutoff))
            .collect(Collectors.toMap(
                r -> (String) r.get("type"),
                r -> signedAmount((String) r.get("type"), ((Number) r.get("amount")).longValue()),
                Long::sum, TreeMap::new));
    }

    static long signedAmount(String type, long amount) {
        if ("REFUND".equals(type)) return -amount;
        if ("FEE".equals(type)) return 25;
        return amount;
    }
}

Version 3: Java 17 (records, enums, switch expressions, toList)

Parse untyped rows once at the boundary into a typed record; business logic then works on types, and the switch expression is exhaustive over the enum.

java
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

enum TxnType { PAYMENT, REFUND, FEE }

record Txn(TxnType type, long amountPaise, LocalDate date) {
    static Txn fromRow(Map<String, Object> row) {
        return new Txn(TxnType.valueOf((String) row.get("type")),
                       ((Number) row.get("amount")).longValue(), (LocalDate) row.get("date"));
    }
    long signedAmount() {
        return switch (type) {
            case PAYMENT -> amountPaise;
            case REFUND -> -amountPaise;
            case FEE -> 25;
        };
    }
}

class ReportJava17 {
    static Map<String, Long> totals(List<Txn> txns, LocalDate today) {
        LocalDate cutoff = today.minusDays(30);
        return txns.stream()
            .filter(t -> !t.date().isBefore(cutoff))
            .collect(Collectors.groupingBy(t -> t.type().name(), TreeMap::new, Collectors.summingLong(Txn::signedAmount)));
    }
}

Version 4: Java 21 (sealed records, pattern matching for switch, sequenced maps)

When each kind of transaction carries different data (a refund references the original payment, a fee has a reason), model them as sealed records and let one exhaustive switch express the rules. SequencedMap gives the first and last entries directly.

java
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.SequencedMap;
import java.util.TreeMap;

sealed interface Txn21 permits Payment21, Refund21, Fee21 {
    LocalDate date();
}
record Payment21(long amountPaise, LocalDate date) implements Txn21 {}
record Refund21(long amountPaise, String originalPaymentId, LocalDate date) implements Txn21 {}
record Fee21(String reason, LocalDate date) implements Txn21 {}

class ReportJava21 {
    static final long FEE_PAISE = 25;

    static Txn21 fromRow(Map<String, Object> row) {
        LocalDate date = (LocalDate) row.get("date");
        long amount = ((Number) row.get("amount")).longValue();
        return switch ((String) row.get("type")) {
            case "PAYMENT" -> new Payment21(amount, date);
            case "REFUND" -> new Refund21(amount, String.valueOf(row.getOrDefault("ref", "unknown")), date);
            case "FEE" -> new Fee21(String.valueOf(row.getOrDefault("reason", "service")), date);
            case String other -> throw new IllegalArgumentException("unknown type " + other);
        };
    }

    static SequencedMap<String, Long> totals(List<Txn21> txns, LocalDate today) {
        LocalDate cutoff = today.minusDays(30);
        TreeMap<String, Long> totals = new TreeMap<>();
        for (Txn21 t : txns) {
            if (t.date().isBefore(cutoff)) continue;
            switch (t) {
                case Payment21(long amount, var date) -> totals.merge("PAYMENT", amount, Long::sum);
                case Refund21(long amount, var ref, var date) -> totals.merge("REFUND", -amount, Long::sum);
                case Fee21 fee -> totals.merge("FEE", FEE_PAISE, Long::sum);
            }
        }
        return totals;
    }
}

class MigrationDemo {
    public static void main(String[] args) {
        LocalDate today = LocalDate.of(2026, 11, 1);
        List<Map<String, Object>> rows = List.of(
            Map.of("type", "PAYMENT", "amount", 10_000, "date", today.minusDays(1)),
            Map.of("type", "PAYMENT", "amount", 5_000, "date", today.minusDays(40)),      // too old
            Map.of("type", "REFUND", "amount", 2_000, "date", today.minusDays(3), "ref", "p-1"),
            Map.of("type", "FEE", "amount", 0, "date", today.minusDays(2)),
            Map.of("type", "PAYMENT", "amount", 7_500, "date", today));

        // Java 7 needs java.util.Date rows: convert for the comparison
        List<Map<String, Object>> legacyRows = new java.util.ArrayList<>();
        for (Map<String, Object> r : rows) {
            Map<String, Object> copy = new java.util.HashMap<>(r);
            copy.put("date", java.util.Date.from(((LocalDate) r.get("date")).atStartOfDay(java.time.ZoneOffset.UTC).toInstant()));
            legacyRows.add(copy);
        }
        java.util.Date legacyToday = java.util.Date.from(today.atStartOfDay(java.time.ZoneOffset.UTC).toInstant());

        Map<String, Long> v7 = ReportJava7.totals(legacyRows, legacyToday);
        Map<String, Long> v8 = ReportJava8.totals(rows, today);
        Map<String, Long> v17 = ReportJava17.totals(rows.stream().map(Txn::fromRow).toList(), today);
        SequencedMap<String, Long> v21 = ReportJava21.totals(rows.stream().map(ReportJava21::fromRow).toList(), today);

        System.out.println(v7 + "\n" + v8 + "\n" + v17 + "\n" + v21);    // {FEE=25, PAYMENT=17500, REFUND=-2000} x4
        System.out.println("identical: " + (v7.equals(v8) && v8.equals(v17) && v17.equals(v21)));
        System.out.println("first=" + v21.firstEntry() + " last=" + v21.lastEntry());
    }
}

How to present the migration

  1. Lock behaviour first: write characterisation tests around the legacy method (the demo's "identical" check) before changing anything.
  2. Java 8: replace Date/millisecond arithmetic with java.time, loops with streams where they read better, nulls with Optional or filtering.
  3. Java 17: parse untyped data once at the boundary into records and enums; use switch expressions; remove casts from business logic.
  4. Java 21: sealed records with pattern matching when variants carry different data; sequenced collections; virtual threads if the method does I/O.
  5. Upgrade the build (--release 21), dependencies (Spring Boot 3 needs Java 17+ and the jakarta.* namespace), and run tools such as OpenRewrite recipes to automate much of the mechanical change.

Feasible → optimal

Every version is O(n). The gains are correctness (no DST bugs, no ClassCastException deep in business logic), readability, and compiler help: exhaustive switches mean adding a new transaction type is caught at compile time instead of being silently counted as a payment.

Follow-up questions interviewers ask

Try answering each one before you open it.

What breaks most often when upgrading a Spring application from Java 8 to 17 or 21?

The javax.* to jakarta.* namespace change when moving to Spring Boot 3; removed Java EE modules (JAXB, JAX-WS) that must be added as dependencies; strong encapsulation of JDK internals (libraries using reflection on sun.* or private fields need upgrades or --add-opens); old versions of Lombok, Mockito, ByteBuddy, ASM and Jacoco that cannot read newer class files; and changed defaults such as TLS versions. Upgrade the build tools and libraries first, then the JDK, then adopt language features gradually.

Should you rewrite all loops as streams during a migration?

No. Migrate for safety and clarity, not fashion. Streams are better for declarative transformations and aggregations; plain loops are often clearer for early exits, complex state, checked exceptions and performance-critical code. Mixed codebases are normal; consistency within a module matters more than using every new feature.