Pattern matching enhancements to switch in Java 17

程序猿DD
中文

Rememberthe instanceof enhancement in Java 16 ?

Recall with the following example:

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

In the above scenario, there are different types of Value values in Map, so use instanceof to determine what type of value is retrieved, and then process them according to different types. Then, let's continue to think about a question. If the Value in this Map may have these types: String, Integer, Double, we need to do different processing for different types. Is the processing structure to be written like this:

 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);
}

Faced with this if statement structure, is it uncomfortable to look at? According to past experience, is it time to use switch to improve it? But after thinking about it again, I found that instanceof was used again in the judgment here. It seems that it is not easy to start again?

So, when faced with this scenario, Java 17 has made enhancements to switch , and then we can write:

 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("");
}

Has it become simpler all of a sudden?

A few highlights here are worth noting:

  1. case condition directly covers the type judgment and type conversion. This function is similar tothe enhancement of instanceof in Java 16.
  2. The processing logic of each case is implemented with the Lambda syntax, which can eliminate the break statement (this is a feature introduced in JDK 12)
In addition, it should be noted that for the function of pattern matching in switch expressions, the implementation in JDK 17 is still the preview version, so understanding is the main thing. It is not recommended for use in the official environment at present, and the possibility of further improvement in the future cannot be ruled out.

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
阅读 693

翟永超,《Spring Cloud微服务实战》作者,Spring Cloud中文社区创始人,SpringForAll社区发起人之一。

2.1k 声望
2.7k 粉丝
0 条评论

翟永超,《Spring Cloud微服务实战》作者,Spring Cloud中文社区创始人,SpringForAll社区发起人之一。

2.1k 声望
2.7k 粉丝
文章目录
宣传栏