How Java 17’s Switch Pattern Matching Simplifies Type Checks
This article demonstrates how Java 17’s enhanced switch statement with pattern matching replaces cumbersome instanceof‑based if‑else chains, providing concise type‑checking and casting for Map values such as String, Integer, and Double, while noting its preview status.
Recently I recorded a video about the instanceof enhancement introduced in Java 16. If you prefer not to watch the video, you can revisit the concept with the following example.
Map<String, Object> data = new HashMap<>();
data.put("key1", "aaa");
data.put("key2", 111);
if (data.get("key1") instanceof String s) {
log.info(s);
}In this scenario the values stored in the map have different types, so instanceof is used to determine the runtime type of the retrieved value before processing it. If the map may contain String, Integer or Double, a typical approach would be a chain of if‑else statements:
if (data.get("key") instanceof String s) {
log.info(s);
} else if (data.get("key") instanceof Double d) {
log.info(d);
} else if (data.get("key") instanceof Integer i) {
log.info(i);
}Such a nested if structure can become cumbersome. Starting with Java 17, the switch statement has been enhanced to support pattern matching, allowing a more concise formulation:
switch (data.get("key1")) {
case String s -> log.info(s);
case Double d -> log.info(d.toString());
case Integer i -> log.info(i.toString());
default -> log.info("");
}The key improvements are:
The case label combines type checking and casting, similar to the instanceof enhancement introduced in Java 16.
Each case can be expressed with a lambda‑style arrow, eliminating the need for a break statement (as introduced by the switch expression enhancements in JDK 14).
Note that pattern‑matching for switch expressions is still a preview feature in JDK 17, so it should be used for learning purposes only and not in production code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
