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 such a if
statement structure, is it uncomfortable to look at? Based on past experience, is it time to use switch
to improve it? But after thinking about it, I found that I used instanceof
when I judged 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:
-
case
condition directly covers the type judgment and type conversion. This function is similar tothe enhancement of instanceof in Java 16. - The processing logic of each
case
is implemented with theLambda
syntax, which can eliminate thebreak
statement (this is a new feature of JDK 14: switch expression enhancement introduced function )
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.
The video corresponding to this content has been recorded, click to view: Java 17 New Features: Pattern Matching of Switch (Preview)
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) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。