Core Java

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:

1
2
3
4
5
6
7
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 with1 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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
public String oldSwitch(int day) {
    final String attr;
    switch (day) {
        case 2,3,4,5,6: {
            attr = "weekday";
            break;
        }
        case  7, 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 theSakila 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) usingmap() in combination with a Switch Expression:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
...
        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:

01
02
03
04
05
06
07
08
09
10
11
12
...
        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:

01
02
03
04
05
06
07
08
09
10
11
12
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:

1
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:

01
02
03
04
05
06
07
08
09
10
11
12
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.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
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:

1
{0=372, 13=223, 17=195, 18=210}

By providing the (optional) groupingBy Map supplierTreeMap::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.

Published on Java Code Geeks with permission by Per Minborg, partner at our JCG program. See the original article here: Java 12: Mapping with Switch Expressions

Opinions expressed by Java Code Geeks contributors are their own.

Per Minborg

I am a guy living in Palo Alto, California, but I am originally from Sweden. I am working as CTO on Speedment with Java and database application acceleration. Check it out on www.speedment.com
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ravindu
Ravindu
5 years ago

That article Really helpful for me thank you.

Back to top button