宝石排列 java_Java 11中的11个隐藏的宝石

Java 11没有引入突破性的功能,但包含了许多你可能还没有听说过的宝石:

1. Lambda参数的类型推断

List> types = /*...*/;

types.stream()// this is fine, but we need @Nonnull on the type.filter(type -> check(type))// in Java 10, we need to do this ~> ugh!.filter((@Nonnull EnterpriseGradeType type) -> check(type))// in Java 11, we can do this ~> better.filter((@Nonnull var type) -> check(type))

2.String :: lines

有多行字符串?想要对每一行做点什么吗?

var multiline = "This\r\nis a\r\nmultiline\r\nstring";

multiline.lines()// we now have a `Stream`.map(line ->"// "+ line)

.forEach(System.out::println);// OUTPUT:// This// is a// multiline// string3.使用'String :: strip'等来剥离空格

4.  用'String :: repeat'重复字符串

5. 使用'Path :: of'创建路径

Path tmp = Path.of("/home/nipa","tmp");

Path codefx = Path.of(URI.create("http://codefx.org"));

6. 使用'Files :: readString'和'Files :: writeString'读取和写入文件

String haiku = Files.readString(Path.of("haiku.txt"));

String modified = modify(haiku);

Files.writeString(Path.of("haiku-mod.txt"), modified);

7. 空读I / O使用'Reader :: nullReader

需要一个丢弃输入字节的 OutputStream吗?需要一个空的 InputStream?使用Reader和Writer但是什么也不做?Java 11让你满意:

InputStream input = InputStream.nullInputStream();

OutputStream output = OutputStream.nullOutputStream();

Reader reader = Reader.nullReader();

Writer writer = Writer.nullWriter();

8. 集合变成一个数组:Collection :: toArray

String[] strings_fun = list.toArray(String[]::new);

9. 使用Optional :: isEmpty表达不存在概念

public boolean needsToCompleteAddress(User user) {

return getAddressRepository()

.findAddressFor(user)

.map(this::canonicalize)

.filter(Address::isComplete)

.isEmpty();

}

10. 使用谓词::not 表达 “不”

Stream.of("a","b","","c")// statically import `Predicate.not`.filter(not(String::isBlank))

.forEach(System.out::println);

11. 使用'Pattern :: asMatchPredicate'作为谓词的正则表达式

Pattern nonWordCharacter = Pattern.compile("\\W");

Stream.of("Metallica","Motörhead")

.filter(nonWordCharacter.asMatchPredicate())

.forEach(System.out::println);

asMatchPredicate是要求整个字符串匹配,而asPredicate 只需要字符串中出现过或有匹配的一段子串即可,要求不高。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值