New features in Java 21: pattern matching for switch

In the previous new features of Java 17, we introduced pattern matching about JEP 406: switch , but at that time it was only the first preview version of this content. Later, it was updated and improved in JDK 18, JDK 19, and JDK 20. Now, in JDK 21, this feature is finalized! Next, we will formally learn this function!

In the previous switch statement, casethere were many restrictions on type matching. For example, in the example below Map, different types of objects may be stored. When we want to judge, we can only rely on if-elseit.

Map<String, Object> data = new HashMap<>();
data.put("key1", "aaa");
data.put("key2", 111);
if (data.get("key1") instanceof String s) {
  log.info(s);
}

if (data.get("key") instanceof String s) {
  log.info(s);
} else if (data.get("key") instanceof Double s) {
  log.info(s);
} else if (data.get("key") instanceof Integer s) {
  log.info(s);
}

From now on, such a type judgment relationship can be simplified to the following switchcode:

switch (data.get("key1")) {
  case String s  -> log.info(s);
  case Double d  -> log.info(d.toString());
  case Integer i -> log.info(i.toString());
  default        -> log.info("");
}

This function is still very useful, especially when there are some abstract encapsulations, and there may be some relationship classes such as father-son, brothers, etc. In order to determine what type it is, there is no need to write a lot of ifs to process, and the simplicity of the code can be further improved. optimization.

For the above example, users who have not yet upgraded to Java 17 also involve two intermediate knowledge points. It is recommended that they learn more: the first is the enhancement of instance of in Java 16 ; the second is the enhancement of using Lambda in switch. .

What if you encounter difficulties while studying? You can join our ultra-high-quality technical exchange group to participate in exchanges and discussions for better learning and progress!

Welcome to follow my public account: Programmer DD. If we had known about cutting-edge technology, there would be hope for overtaking on curves! To accumulate overtaking capital, start by paying attention to DD!

Guess you like

Origin blog.csdn.net/dyc87112/article/details/133070414