Java 20: Record Patterns and the enhanced For Loop

With Java 20 released, Project Amber further iterated on Record Patterns with JEP 432, the second preview of this new feature. This time they implemented support for record patterns in the enhanced for loop.

If you don’t know what record patterns are, just check out my previous post about the topic, which explains this new language feature in detail.

But let’s dive straight into some code and see the new syntax in action:

public class RecordPatternsForLoopExample {
   
    private static void printMonkeyData(){
        List<Monkey> monkeys = List.of( 
             new Monkey("Bert", 2),
             new Monkey("Jeff", 5),
             new Monkey("Ernie", 7));
        for (Monkey(String name, int age) : monkeys){
            System.out.println("Monkey "+name+" is "+age+" years old.");
        }
    }
}

record Monkey(String name, int age){}

In line (14) we specify a simple record of type Monkey with two properties: name and age. From line (4) to (7) we create a couple of Monkey instances and put them all together into a List. The new enhanced for loop comes into action from line (8) to (10). We iterate over the list of Monkeys and extract the two properties name and age into local variables by using a record pattern. These two can then be used within the for loop block like in the println statement on line (9).

This new mechanism also works on nested records. Let’s expand our example with a couple more records that nest in each other:

record Monkey(String name, int age){}
record Donkey(String name, int age){}
record Zoo(Monkey monkey, Donkey donkey){}

There is a new record Donkey specified in line (2) and a new record Zoo in line (3). The Zoo record consists of a single Monkey and Donkey as properties. It is a very small zoo.

Let’s create a couple of Zoo instances in a List and iterate over it with the new enhanced for loop:

 private static void printZooData() {
    List<Zoo> zoos = List.of(
        new Zoo(new Monkey("Jeff",5), new Donkey("Bob", 4)),
        new Zoo(new Monkey("Charles",5), new Donkey("Sierra", 12)));
    for (Zoo(Monkey(String mName, int mAge),
         Donkey(String dName, int dAge)) : zoos) {
       System.out.println(
        "The zoo has a monkey called "+mName+ " and a donkey called "+dName);
    }
}

You can see in line (5) and (6) how the record pattern works with a nested data structure. The name and age of Donkeys and Monkeys can be extracted directly out of the Zoo record by using the nested record pattern syntax. The definition of the patterns is quite complex, but saves a lot of code accessing the nested properties by getters.

I think this is a great enhancement for the new record pattern syntax since the enhanced for loop is used a lot more than he previously implemented instanceof and switch syntax.

The only drawback that I can still see is that you have to define all properties of a record within a pattern. If your records are nested and have a dozen properties each, the record patterns will just be to complex to write if you only want to access some of properties within the for loop. Let’s wait and see what Project Amber is going to come up with to make this syntax also usable with more complex data structures.

As always, you can find the code examples here on Github.


Beitrag veröffentlicht

in

von

Schlagwörter:

Kommentare

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert