Wednesday, March 27, 2019

Java 12: Mapping with Switch Expressions

Java 12: Mapping with Switch Expressions

In this article, we will be looking at the new Java 12 feature “Switch Expressions” and how it can be used in conjunction with the Stream::map operation and some other Stream operations. Learn how you can make your code better with Streams and Switch Expressions.

Switch Expressions

Java 12 comes with “preview” support for “Switch Expressions”. Switch Expression allows switch statements to return values directly as shown hereunder:

public String newSwitch(int day) {
    return switch (day) {
        case 2, 3, 4, 5, 6 -> "weekday";
        case 7, 1 -> "weekend";
        default -> "invalid";
    } + " category";
}
Invoking this method with 1 will return “weekend category”.

This is great and makes our code shorter and more concise. We do not have to bother will fall-through concerns, blocks, mutable temporary variables or missed cases/default that might be the case for the good ole’ switch. Just look at this corresponding old switch example and you will see what I mean:
public String oldSwitch(int day) {
    final String attr;
    switch (day) {
        case 2: case 3: case 4: case 5: case 6: {
            attr = "weekday";
            break;
        }
        case 7: case 1: {
            attr = "weekend";
            break;
        }
        default: {
            attr = "invalid";
        }
    }
    return attr + " category";
}

Switch Expressions is a Preview Feature

In order to get Switch Expression to work under Java 12, we must pass “--enable-preview” as a command line argument both when we compile and run our application. This proved to be a bit tricky but hopefully, it will get easier with the release of new IDE versions and/or/if Java incorporates this feature as a fully supported feature. IntelliJ users need to use version 2019.1 or later.

Switch Expressions in Stream::map

Switch Expressions are very easy to use in Stream::map operators, especially when compared with the old switch syntax. I have used Speedment Stream ORM and the Sakila exemplary database in the examples below. The Sakila database is all about films, actors and so forth.

Here is a stream that decodes a film language id (a short) to a full language name (a String) using map() in combination with a Switch Expression:

public static void main(String... argv) {

    try (Speedment app = new SakilaApplicationBuilder()
        .withPassword("enter-your-db-password-here")
        .build()) {

        FilmManager films = app.getOrThrow(FilmManager.class);

        List<String> languages = films.stream()
            .map(f -> "the " + switch (f.getLanguageId()) {
                case 1 -> "English";
                case 2 -> "French";
                case 3 -> "German";
                default -> "Unknown";
            } + " language")
            .collect(toList());

        System.out.println(languages);
    }
}
This will create a stream of all the 1,000 films in the database and then it will map each film to a corresponding language name and collect all those names into a List. Running this example will produce the following output (shortened for brevity):

[the English language, the English language, … ]

If we would have used the old switch syntax, we would have gotten something like this:
        ...
        List<String> languages = films.stream()
            .map(f -> {
                final String language;
                switch (f.getLanguageId()) {
                    case 1: {
                        language = "English";
                        break;
                    }
                    case 2: {
                        language = "French";
                        break;
                    }
                    case 3: {
                        language = "German";
                        break;
                    }
                    default: {
                       language = "Unknown";
                    }
                }
                return "the " + language + " language";
            })
            .collect(toList());
        ...
Or, perhaps something like this:
        ...
        List<String> languages = films.stream()
            .map(f -> {
                switch (f.getLanguageId()) {
                    case 1: return "the English language";
                    case 2: return "the French language";
                    case 3: return "the German language";
                    default: return "the Unknown language";
                }
            })
            .collect(toList());
         ...
The latter example is shorter but duplicates logic.

Switch Expressions in Stream::mapToInt

In this example, we will compute summary statistics about scores we assign based on a film’s rating. The more restricted, the higher score according to our own invented scale:
IntSummaryStatistics statistics = films.stream()
    .mapToInt(f -> switch (f.getRating().orElse("Unrated")) {
        case "G", "PG" ->  0;
        case "PG-13"   ->  1;
        case "R"       ->  2;
        case "NC-17"   ->  5;
        case "Unrated" -> 10;
        default -> 0;
    })
    .summaryStatistics();

 System.out.println(statistics);
This will produce the following output:
IntSummaryStatistics{count=1000, sum=1663, min=0, average=1.663000, max=5}

In this case, the difference between the Switch Expressions and the old switch is not that big. Using the old switch we could have written:

IntSummaryStatistics statistics = films.stream()
    .mapToInt(f -> { 
        switch (f.getRating().orElse("Unrated")) {
            case "G": case "PG": return 0;
            case "PG-13":   return 1;
            case "R":       return 2;
            case "NC-17":   return 5;
            case "Unrated": return 10;
            default: return 0;
        }
    })
   .summaryStatistics();

Switch Expressions in Stream::collect

This last example shows the use of a switch expression in a grouping by Collector. In this case, we would like to count how many films that can be seen by a person of a certain minimum age. Here, we are using a Map with the minimum age as keys and counted films as values.
Map<Integer, Long> ageMap = films.stream()
     .collect(
         groupingBy( f -> switch (f.getRating().orElse("Unrated")) {
                 case "G", "PG" -> 0;
                 case "PG-13"   -> 13;
                 case "R"       -> 17;
                 case "NC-17"   -> 18;
                 case "Unrated" -> 21;
                 default -> 0;
             },
             TreeMap::new,
             Collectors.counting()
          )
      );

System.out.println(ageMap);
This will produce the following output:
{0=372, 13=223, 17=195, 18=210}
By providing the (optional) groupingBy Map supplier TreeMap::new, we get our ages in sorted order. Why PG-13 can be seen from 13 years of age but NC-17 cannot be seen from 17 but instead from 18 years of age is mysterious but outside the scope of this article.

Summary

I am looking forward to the Switch Expressions feature being officially incorporated in Java. Switch Expressions can sometimes replace lambdas and method references for many stream operation types.

Resources

Sakila: https://dev.mysql.com/doc/index-other.html or https://hub.docker.com/r/restsql/mysql-sakila
JDK 12 Download: https://jdk.java.net/12/
Speedment Stream ORM Initializer: https://www.speedment.com/initializer/