Java
Pattern Matching
instanceof pattern matching.
By EZ4Code Team
pattern-matchingtype
Code
// instanceof pattern matching (Java 16+)
Object obj = "Hello World";
if (obj instanceof String s) {
System.out.println(s.length());
System.out.println(s.toUpperCase());
}
// switch pattern matching (Java 21+)
String describe(Object o) {
return switch (o) {
case Integer i -> "Integer: " + i;
case String s -> "String: " + s;
case null -> "null";
case int[] arr -> "Array of length " + arr.length;
default -> "Unknown: " + o;
};
}
// Pattern with guard
String check(Object o) {
return switch (o) {
case String s when s.length() > 5 -> "Long string";
case String s -> "Short string";
default -> "Not a string";
};
}Explanation
Pattern matching simplifies type checking and conversion; switch pattern matching supports type patterns and guard conditions.
More Java Snippets
String Operations and StringBuilder
Manipulate strings with split, join, substring, and StringBuilder in Java.
Stream API
Process collections using the Stream API.
Lambda Expressions
Simplify code with Lambda expressions.
Optional
Handle null values elegantly.
Collection Operations
Common operations on List, Set, and Map.
Exception Handling
try-catch-finally and custom exceptions.