Switch 表达式
在 Java 14 及以上版本中,可以使用 switch 表达式来返回一个值。参见 JEP 361: Switch Expressions。
int number = 7;
String word =
switch (number) {
case 0 -> "ZERO";
case 1 -> "ONE";
case 2 -> "TWO";
case 3 -> "THREE";
case 4 -> "FOUR";
case 5 -> "FIVE";
case 6 -> "SIX";
case 7 -> "SEVEN";
case 8 -> "EIGHT";
case 9 -> "NINE";
default -> "N/A";
};
输出结果将是:
word = SEVEN
作为另一个例子,可以将这个 switch
语句放入一个方法中。
private static String digitToWord(final int x) {
return switch (x) {
case 0 -> "ZERO";
case 1 -> "ONE";
case 2 -> "TWO";
case 3 -> "THREE";
case 4 -> "FOUR";
case 5 -> "FIVE";
case 6 -> "SIX";
case 7 -> "SEVEN";
case 8 -> "EIGHT";
case 9 -> "NINE";
default -> "N/A";
};
}
调用该方法进行练习:
IntStream.rangeClosed(0, 10)
.forEach(i -> System.out.println(i + " = " + digitToWord(i)));
输出将会是:
0 = ZERO
1 = ONE
2 = TWO
3 = THREE
4 = FOUR
5 = FIVE
6 = SIX
7 = SEVEN
8 = EIGHT
9 = NINE
10 = N/A