DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Using Python Libraries in Java
  • Designing a Java Connector for Software Integrations
  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs

Trending

  • How To Develop a Truly Performant Mobile Application in 2025: A Case for Android
  • Performance Optimization Techniques for Snowflake on AWS
  • Streamlining Event Data in Event-Driven Ansible
  • Contextual AI Integration for Agile Product Teams
  1. DZone
  2. Coding
  3. Java
  4. Java 12: Mapping With Switch Expressions

Java 12: Mapping With Switch Expressions

Learn more about mapping with the latest Java 12 switch expressions.

By 
Per-Åke Minborg user avatar
Per-Åke Minborg
·
Mar. 28, 19 · Presentation
Likes (16)
Comment
Save
Tweet
Share
33.5K Views

Join the DZone community and get the full member experience.

Join For Free

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 with 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/ 

Java (programming language)

Published at DZone with permission of Per-Åke Minborg, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Using Python Libraries in Java
  • Designing a Java Connector for Software Integrations
  • How to Convert XLS to XLSX in Java
  • Recurrent Workflows With Cloud Native Dapr Jobs

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!