Faced with such a if
statement, do you feel uncomfortable?
if (flag == 1) {
log.info("didispace.com: 1");
} else if (flag == 2) {
log.info("didispace.com: 2");
} else if (flag == 3) {
log.info("didispace.com: 3");
} else if (flag == 4) {
log.info("didispace.com: 4");
} else {
log.info("didispace.com: x");
}
Are you thinking of using switch
to improve it?
switch(flag) {
case 1:
log.info("didispace.com: 1");
break;
case 2:
log.info("didispace.com: 2");
break;
case 3:
log.info("didispace.com: 3");
break;
case 4:
log.info("didispace.com: 4");
break;
default:
log.info("didispace.com: x");
}
Are you comfortable? Do you still feel uncomfortable?
Try out the enhancements to Switch expressions in Java 14 and continue the transformation:
switch(flag) {
case 1 -> log.info("didispace.com: 1");
case 2 -> log.info("didispace.com: 2");
case 3 -> log.info("didispace.com: 3");
case 4 -> log.info("didispace.com: 4");
default -> log.info("didispace.com: x");
}
Are you comfortable now? In Java 14's switch expression enhancements, support for Lambda syntax was introduced, making each case branch more concise. At the same time, the easy to forget break
can also be omitted.
Tips: The JEP 361 feature here was finalized in JDK 14 after two preview versions of JDK 12 and JDK 13, so some functions will also be seen in JDK 12 and JDK 13, but for real use, it is recommended to use JDK 14 and later versions.
Well, today's sharing is here! If you encounter difficulties in the learning process? You can join our high-quality technical exchange group , participate in exchanges and discussions, and learn and progress better! Also, don't walk away, follow me! Continue to update the new Java feature column !
Welcome to my public account: Programmer DD. Learn about cutting-edge industry news for the first time, share in-depth technical dry goods, and obtain high-quality learning resources
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。