Java Patterns
This feature has been rolling out since Java 16, with more to come in future updates. Pattern matching checks the structure of an object, and then extracts the data based on these patterns. This makes code easier to read.
There are currently four pattern matching features.
Java 16 - Pattern Matching for instanceof
Consider the following:
sealed interface Animal permits Dog, Cat {}
record Dog(LicenseName name, String breed) implements Animal {}
record Cat(String name, String breed) implements Animal {}
record LicenseName(String fullName, String nickname) {}
We can check to see if an element of ArrayList animList
is of type Dog
by using instanceof
.
ArrayList<Animal> animList = new ArrayList<>();
for (Animal a: animList) {
//without patterns
if (a instanceof Dog) {
Dog dog = (Dog)a;
//do something with dog
}
//with patterns
if (a instanceof Dog dog) {
//do something with dog
}
}
In using patterns, the code a instanceof Dog dog
checks to see if a
is a Dog
and then declares and creates dog
as a Dog
object and assigns it to a
.
Java 21 - Record Patterns
Record Patterns decompose the record into the individual instance variables.
For example, instead of:
if (a instanceof Dog dog) {
System.out.println (dog.name().fullName());
}
We could use Record patterns and write:
if (a instanceof Dog(LicenseName (String fullName, String nicName), String breed) {
System.out.println(fullName);
}
Java 21 - Pattern Matching for Switch
Similar to Record Patterns, the Pattern Matching for Switch includes:
- a type check in the form of case checks;
- creation and assignment of variable; and
- typecasting of the variable.
For example:
for (Animal a : animList) {
switch (a) {
//uses pattern matching to declare dog and assign it to (Dog)a
case Dog dog: {
System.out.println(dog.name().fullName());
break;
}
case Cat cat: {
System.out.println(cat.name());
break;
}
}
}
Java 22 - Unnamed Variables and Patterns
Allows us to use the underscore ( _
) for variable names that will not be used. In the following code for try... catch
statements, an Exception variable is not used, so we can write:
try {
//something
} catch (Exception _ ) {
//error message
}
In another example, using Pattern Matching for Switch, we can print the animals' names using the following:
for (Animal a : animList) {
switch (a) {
case Dog(LicenseName(_, String nickName), _ ) -> System.out.println(nickName);
case Cat(String name, _ ) -> System.out.println(name);
}
}
Since we are using a sealed interfaces that only allows implementation with Dog
and Cat
, a default statement is not necessary.
Resources
Veterinarian Office - Pattern Matching Mini-Lab
For more on Pattern Matching and what's to come, check out this video by Nicolai Parlog.