Java 11中的11个隐藏的宝石


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

1. Lambda参数的类型推断

List<EnterpriseGradeType<With, Generics>> 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<With, Generics> 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<String>`
    .map(line ->
"// " + line)
    .forEach(System.out::println);
 
// OUTPUT:
// This
// is a
// multiline
// string

3. 
使用'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 只需要字符串中出现过或有匹配的一段子串即可,要求不高。