- 2023-01-24 11:11:46
- 2001 热度
- 0 评论
上一篇说完了Java11的新特性,本篇接着说一下Java12.Java 12 对开发者有用的特性并不是特别多,不过实用性还是有的。
字符串增强
Java 12 进一步对字符串操作进行增强,增加了两个方法。
字符串缩进
String indent(int n)
会根据参数n
对字符串进行缩进。具体的规则是
- 当
n>0
时,会在字符串的每一行开头插入n
个空格,字符串整体右移。 - 当
n<0
时,会在字符串的每一行开头删除n
个空格,如果实际的空格数小于n
,删除该行所有空格,但是并不会换行。
来实验一下:
String text = " Hello \n Java12"; |
对应的结果是:
字符串转换
String
增加了一个transform
方法,将字符串操作函数化。
<R> R transform(Function<? super String, ? extends R> f) |
目的是加强字符串的函数操作。举个例子:
String txt = "hello "; |
Java的每一个版本都在加强函数式编程。
基于内容的文件匹配
Java 12 在Files
工具类中增加了一个新的静态方法Files.mismatch(Path,Path)
,用来找两个文件内容(byte
)不一样的地方,返回两个文件内容中第一个不匹配字节的位置,如果没有不匹配,则返回-1L
。
// 文件对比 |
该方法和另外一个方法Files.isSameFile(Path, Path)
的效果有点类似,但是还是有区别的。
Collectors::teeing
对Stream流的聚合操作Collector
进一步增强,增加了teeing
操作来实现一些复杂的聚合操作。举个例子,我如果想统计一个数组的平均数在总和的占比,首先要计算平均数,然后再计算总和,然后再相除,这样需要三个步骤。
Double average = Stream.of(1, 2, 3, 4, 5).collect(Collectors.averagingDouble(i -> i)); |
用了teeing
之后就可以一步完成:
Double meanPercentage = Stream.of(1, 2, 3, 4, 5) |
新的数字格式化
Java 12 引入了新的基于区域的紧凑型数字化格式类CompactNumberFormat
,用来对长数字进行简写。通常程序员喜欢把工资区间标为10k-20k
,而其它一些行业喜欢10000-20000
。
NumberFormat chnFormat = NumberFormat.getCompactNumberInstance(Locale.CHINA, NumberFormat.Style.SHORT); |
你还可以自定义
CompactNumberFormat
来实现个性化的数字格式化。
其它
除了上面以外,Java12还有一些预览属性和JVM增强功能,并没有太多的亮点。
0 评论
留下评论
热门标签
- Spring(403)
- Boot(208)
- Spring Boot(187)
- Spring Cloud(82)
- Java(82)
- Cloud(82)
- Security(60)
- Spring Security(54)
- Boot2(51)
- Spring Boot2(51)
- Redis(31)
- SQL(29)
- Mysql(25)
- IDE(24)
- Dalston(24)
- MVC(22)
- JDBC(22)
- IDEA(22)
- mongoDB(22)
- Web(21)
- CLI(20)
- SpringMVC(19)
- Alibaba(19)
- Docker(17)
- SpringBoot(17)
- Git(16)
- Eclipse(16)
- Vue(16)
- ORA(15)
- JPA(15)
- Apache(15)
- Tomcat(14)
- Linux(14)
- HTTP(14)
- Mybatis(14)
- Oracle(14)
- jdk(14)
- Pro(13)
- XML(13)
- JdbcTemplate(13)
- OAuth(13)
- Nacos(13)
- Data(12)
- JSON(12)
- OAuth2(12)
- Myeclipse(11)
- stream(11)
- int(11)
- not(10)
- Bug(10)
- Hystrix(9)
- ast(9)
- maven(9)
- Map(9)
- Swagger(8)
- APP(8)
- Bit(8)
- API(8)
- session(8)
- Window(8)
- HTML(7)
- Github(7)
- JavaMail(7)
- Cache(7)
- File(7)
- IntelliJ(7)
- mail(7)
- windows(7)
- too(7)
- ehcache(6)
- UDP(6)
- RabbitMQ(6)
- and(6)
- star(6)
- Excel(6)
- Log4J(6)
- pushlet(6)
- apt(6)
- read(6)
- Freemarker(6)
- WebFlux(6)
- JSP(6)
- Bean(6)
- error(6)
- nginx(6)
- Server(6)
- jar(6)
- ueditor(6)
- Sentinel(5)
- the(5)
- JWT(5)
- rdquo(5)
- PHP(5)
- Struts(5)
- string(5)
- script(5)
- Syntaxhighlighter(5)
- Tool(5)
- Controller(5)
- swagger2(5)