Return to site
Modern Java toys that boost productivity, from type inference to text blocks
·
Local variable type inference
Removes redundant code and saves a lot of typing.
AccountsOverviewPage accountsOverviewPage = page.login(username, password);
becomes
var accountsOverviewPage = page.login(username, password);
Stream API: takeWhile and dropWhile
- The takeWhile() operation processes the items of a collection and keeps each one while a given condition is true.
- The dropWhile() operator does the opposite: It disregards the items of a collection while the predicate is true.
Switch expressions
Java 12 introduced switch expressions, which enable you to use switch to directly assign a value to a variable.
String id = switch(name) { case "john" -> "12212"; case "mary" -> "4847474"; case "tom" -> "293743"; default -> ""; };
Records
Records are great for simple classes that only need to contain fields and access to those fields.
public record Account( int id, int customerId, String type, double balance) {}
Text blocks
It allows you to use three quotation marks to open and close a big block of text.
return """ { "id": 13344, "customerId": 12212, "type": "CHECKING", "balance": 3821.93 } """;