Previously, I wrote about "Record Patterns" introduced in Java 19, that allow you to "deconstruct" records and access their components directly.
In Java 20 (released a couple of weeks ago!), record patterns have been enhanced so that they can also be used in for loops.
Here is an example that uses a nested record pattern in a for loop to print out a list of records:
record Author(String firstName, String lastName) {}
record Book(String title, Author author, double price) {}
static void printBooks(List<Book> books) {
for (Book(var title, Author(var firstName, var lastName), var price): books) {
System.out.printf("%s by %s %s for %.2f\n", title, firstName, lastName, price);
}
}
Related post:Java 19: Record Patterns
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.