switch multi value match Sao operation, take you up posture!

Keywords: Programming Java Lambda

We all know that switch is used to go through process branches, and in most cases to match a single value, as shown in the following example:

/**
 * @from WeChat public address: Java technology stack
 * @author Stack length
 */
private static void test(int value) {
    switch (value) {
        case 1:
            System.out.println("1");
            break;
        case 2:
            System.out.println("1");
            break;
        case 3:
            System.out.println("1");
            break;
        case 4:
            System.out.println("1");
            break;
        case 5:
            System.out.println("1");
            break;
        case 6:
            System.out.println("0");
            break;
        case 7:
            System.out.println("0");
            break;
        default:
            System.out.println("-1");
    }
}

Related reading: Six data types supported by switch case.

Roughly speaking, output from Monday to Friday: 1, output from Saturday to Sunday: 0, default output - 1.

In this way, a lot of repetitive logic is redundant.

Maybe this example is not very suitable. It is more appropriate to use if/ else, but this is just an example. In actual development, there must be several case s matching the same logic.

So, how can multiple case s match the same logic?

As shown in the following example:

/**
 * @from WeChat public address: Java technology stack
 * @author Stack length
 */
private static void test(int value) {
    switch (value) {
        case 1: case 2: case 3: case 4: case 5:
            System.out.println("1");
            break;
        case 6: case 7:
            System.out.println("0");
            break;
        default:
            System.out.println("-1");
    }
}

Put the cases of the same logic together, and the last case will write logic.

This is how it is formatted:

/**
 * @from WeChat public address: Java technology stack
 * @author Stack length
 */
private static void test(int value) {
    switch (value) {
        case 1: 
        case 2: 
        case 3: 
        case 4: 
        case 5:
            System.out.println("1");
            break;
        case 6: 
        case 7:
            System.out.println("0");
            break;
        default:
            System.out.println("-1");
    }
}

Is it very coquettish?

In fact, this is not the most appropriate and best way to write. In Java 12, it can be more elegant.

In Java 12, you can use commas to separate multiple values, lambda expressions, and even omit break. It is more convenient to use switch. See this article for details: Java 12 Sao operation, switch can play like this Or pay attention to WeChat public number: Java technology stack, back to "new features" in the background to get this article.

Posted by All4172 on Sat, 04 Jan 2020 15:11:47 -0800