JDK9-15的新特性
内容学习自知秋老师的翻译课程
copyOf方法
代码示例
package com.wxit.api;
import java.util.ArrayList;
import java.util.List;
/**
* @author wj
* @date 2021.09.25 09:49
*/
public class CopyOfApiDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("吴杰");
names.add("婷姐");
names.add("佳伟");
List<String> copyOfNames = List.copyOf(names);
doNotChange(copyOfNames);
System.out.println(copyOfNames);
}
private static void doNotChange(List<String> copyOfNames) {
copyOfNames.add("子龙");
}
}
jdk11中引进的方法writeString 和 readString
代码示例
package com.wxit.api;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* @author wj
* @date 2021.09.26 20:58
*/
public class FileReadWriteRunner {
/*
可以看到,使用这些特定的新方法,readString 和 writeString 使得从文件中读取可写入变的更加容易
*/
public static void main(String[] args) throws IOException {
Path path = Paths.get("./resource/sample.txt");
String fileContent = Files.readString(path);
System.out.println(fileContent);
String newFileContent = fileContent.replace("wujie", "xiaohao");
Path newFilePath = Paths.get("./resource/sample-new.txt");
Files.writeString(newFilePath,newFileContent);
}
}
jdk11中引进的Predicate.not方法
代码示例
package com.wxit.api;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;
/**
* @author wj
* @date 2021.09.26 21:16
*/
public class PredicateNotRunner {
public static void main(String[] args) {
List<Integer> numbers = List.of(12,25,36,24,13,125);
Predicate<Integer> evenNumberPredicate = number -> number % 2 ==0;
// Stream<Integer> integerStream = numbers.stream().filter(evenNumberPredicate);
// integerStream.forEach(s -> System.out.println(s));
numbers.stream().filter(evenNumberPredicate.negate()).forEach(System.out::println);
}
}