为什么要写这篇文章

经过了若干年的发展,Java逐步从java8升级为java11java17

让我们对比学习一下最新一版的LTS版本和java8比起来让代码简化了多少。

  1. 文本块(Text Blocks)。

这个写法有些类似于 javascript、 Lua等脚本语言。方便识别html、json等格式复杂的字符串。

public class StringTest {
public static void main(String[] args) throws Exception {
// 传统写法
String json =
"{\n" +
" \"key\":\"a\",\n" +
" \"value\":\"b\"\n" +
"}";
// 优化后写法
String json2 = """
{
"key":"a",
"value":"b"
}
""";
// 返回为 true
System.out.println(json == json2);
}
}
  1. 本地变量类型推断(Local Variable Type Inference)

这一点也是在一些脚本语言中常见的,类似于 var 表示变量,val 表示常量。

    public static void main(String[] args) throws Exception {
//集合
// immutable map build
var map = Map.of(
"cat", "猫",
"dog", "狗",
"fish", "鱼");
// immutable set build
var set = Set.of("1", "2", "3");
// immutable list build
var list = List.of(1, 2, 3, 4, 5); // 循环语句
for (var i = 1; i < list.size(); i++) {
System.out.println(i);
}
for (var i : list) {
System.out.println(i);
} // 异常
try (var in = new ByteArrayInputStream("123".getBytes())) {
System.out.println(new String(in.readAllBytes(), "utf-8"));
} catch (Exception e) {
System.out.println(e);
} // lambda 表达式 意思相同
BiFunction<Integer, Integer, Integer> biFunction = (a, b) -> a + b;
BiFunction<Integer, Integer, Integer> biFunction2 = (var a, var b) -> a + b;
}
  1. switch
    public static void main(String[] args) throws Exception {
var eating = Eating.BREAKFAST;
String eatingZnString = "";
// 传统写法
switch (eating) {
case BREAKFAST:
case LUNCH:
eatingZnString = "早午饭";
break;
case DINNER:
eatingZnString = "晚饭";
break;
default:
throw new Exception();
}
System.out.println(eatingZnString); // 优化后写法
System.out.println(
switch (eating) {
case BREAKFAST,LUNCH -> "早午饭";
case DINNER -> "晚饭";
default -> throw new Exception();
}
);
}
  1. instance of操作符的模式匹配(Pattern Matching for the instanceof Operator)

interface Animal {} class Cat implements Animal {
public void mew() {
System.out.println("喵");
}
} class Dog implements Animal {
public void woof() {
System.out.println("汪");
}
} public class Test {
// 传统写法
public static void sounds(Animal animal) {
if (animal instanceof Cat) {
Cat cat = (Cat) animal;
cat.mew();
} else if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.woof();
} else {
throw new IllegalArgumentException("没有这种动物的叫声");
}
} // 优化写法
public static void betterSounds(Animal animal) {
if (animal instanceof Cat cat) {
cat.mew();
} else if (animal instanceof Dog dog) {
dog.woof();
} else {
throw new IllegalArgumentException("没有这种动物的叫声");
}
}
}
  1. record 类
// 传统类
public record People(String name, int age) {
public People(String name, int age) {
this.name = name;
this.age = age;
} public String name() {
return this.name;
} public int age() {
return this.age;
}
public boolean equals(People people) {...}
public int hashCode() {...}
public String toString() {...}
} // 优化后的类
public record People (String name, int age){ } // 更多用法
public record People (String name, int age){
// 静态字段
static int teenageAge; // 静态初始化
static {
teenageAge = 17;
}
// 静态方法
public static People buildTeenage(String name) {
return new People(name , teenageAge);
} // 优化后的构造方法
public People {
if (age < 0) {
throw new IllegalArgumentException("年龄不能小于0");
}
}
}

参考文档

Java Language Updates

Java 8 后的新功能梳理的更多相关文章

  1. Java 17 将要发布,补一下 Java 13 中的新功能

    本文章属于Java 新特性教程 系列,已经收录在 Github.com/niumoo/JavaNotes ,点个赞,不迷路. 自从 Oracle 调整了 Java 的版本发布节奏之后,Java 版本发 ...

  2. Java 14 新功能介绍

    不做标题党,认认真真写个文章. 文章已经收录在 Github.com/niumoo/JavaNotes 和未读代码博客,点关注,不迷路. Java 14 早在 2019 年 9 月就已经发布,虽然不是 ...

  3. Java 16 新功能介绍

    点赞再看,动力无限.Hello world : ) 微信搜「程序猿阿朗 」. 本文 Github.com/niumoo/JavaNotes 和 程序猿阿朗博客 已经收录,有很多知识点和系列文章. Ja ...

  4. Java 17 新功能介绍(LTS)

    点赞再看,动力无限.Hello world : ) 微信搜「程序猿阿朗 」. 本文 Github.com/niumoo/JavaNotes 和 未读代码博客 已经收录,有很多知识点和系列文章. Jav ...

  5. Java 11 新功能来了!

    关键时刻,第一时间送达! 目前 Oracle 已经发布了 Java Development Kit 10,下个版本 JDK 11 也即将发布.本文介绍 Java 11 的新功能. 根据Oracle新出 ...

  6. Java 11新功能抢先了解

    目前 Oracle 已经发布了 Java Development Kit 10,下个版本 JDK 11 也即将发布.本文介绍 Java 11 的新功能. 根据Oracle新出台的每6个月发布一次Jav ...

  7. 面试题思考:Java 8 / Java 7 为我们提供了什么新功能

    Java 7 的7个新特性 1.对集合类的语言支持: 2.自动资源管理: 3.改进的通用实例创建类型推断: 4.数字字面量下划线支持: 5.switch中使用string: 6.二进制字面量: 7.简 ...

  8. 超详细 Java 15 新功能介绍

    点赞再看,动力无限.微信搜「程序猿阿朗 」,认认真真写文章. 本文 Github.com/niumoo/JavaNotes 和 未读代码博客 已经收录,有很多知识点和系列文章. Java 15 在 2 ...

  9. Java 19 新功能介绍

    点赞再看,动力无限. 微信搜「程序猿阿朗 」. 本文 Github.com/niumoo/JavaNotes 和 未读代码博客 已经收录,有很多知识点和系列文章. Java 19 在2022 年 9 ...

随机推荐

  1. 一类巧妙利用利用失配树的序列DP

    I.导入 求长度为\(\text{len}\)的包含给定连续子串\(\text{T}\)的 0/1 串的个数.(\(|T|<=15\)) 通常来说这种题目应该立刻联想到状压 DP 与取反集--这 ...

  2. PAML 选择压力的计算

    简介 PAML(Phylogenetic Analysis by Maximum Likelihood)是伦敦大学的杨子恒(Yang Ziheng)教 授开发的一套基于最大似然估计来对蛋白质和核酸序列 ...

  3. ss 显示socket状态

    ss ===show socket用于显示socket状态 所有的TCP sockets 所有的UDP sockets 所有ssh/ftp/ttp/https持久连接 所有连接到Xserver的本地进 ...

  4. shell 脚本自动插入文件头

    vim编辑shell脚本自动插入文件头部信息,将下面的代码写入home目录xia .vimrc 文件即可. shell 文件头: 1 autocmd BufNewFile *.sh exec &quo ...

  5. Redis键空间通知(keyspace notification),事件订阅

      Redis键空间通知(keyspace notification),事件订阅   应用场景:有效期优惠券.24小时内支付.下单有效事件等等. 功能概览 键空间通知使得客户端可以通过订阅频道或模式, ...

  6. Linux—yum安装python-pip

    centos下安装pip时失败: [root@wfm ~]# yum -y install pipLoaded plugins: fastestmirror, refresh-packagekit, ...

  7. 模拟串口UART的实现

    我所祷告的,就是要你们的爱心,在知识和见识上,多而又多,使你们能分辨是非,做诚实无过的人,直到基督的日子.--腓立比书[1:9~10] 最近在调的MCU的型号为STM32F030,配置芯片相较之前的M ...

  8. 巩固javaweb第十天

    巩固内容: HTML <meta> 元素 meta标签描述了一些基本的元数据. <meta> 标签提供了元数据.元数据也不显示在页面上,但会被浏览器解析. META 元素通常用 ...

  9. Linux学习 - 系统定时任务

    1 crond服务管理与访问控制 只有打开crond服务打开才能进行系统定时任务 service crond restart chkconfig crond on 2 定时任务编辑 crontab [ ...

  10. mysql explain using filesort

    创建表,字段tid上无索引(mysql 5.7) CREATE TABLE `test` ( `tid` int(11) DEFAULT NULL, `tname` varchar(12) DEFAU ...