java 11 special

143 阅读1分钟

class a {


    public static void main(String[] args) {
        List<String> list = new ArrayList<>() {

        };
        list.add("a");
        list.add("d");
        List<String> list1 = list.stream()
                .filter(Predicate.not(x -> x == "d"))
                .collect(Collectors.toList());
        System.out.println(list1);
/*Java11在lambda参数中新增了本地变量语法(var 关键字)。
可以给本地变量添加修饰语,比如添加一个自定义注解*/
        List<String> sampleList = Arrays.asList("Java", "Kotlin");
        String resultString = sampleList.stream()
                .map((var x) -> x.toUpperCase())
                .collect(Collectors.joining(", "));
        System.out.println(resultString);
        //assertThat(resultString).isEqualTo("JAVA, KOTLIN");


    }

    /*
     * Predicate方法新增了一个静态not方法,很像negate方法,用来否定一个存在的Predicate
     * */
    static <T> Predicate<T> not(Predicate<? super T> target) {
        Objects.requireNonNull(target);
        return (Predicate<T>) target.negate();
    }
}

/*
*
* java.net.http包的新HTTP client是在Java 9 引进的,在Java11成为了一个标准的特性 。
新的HTTP API 提升了整体性能并且支持HTTP/1.1和 HTTP/2
* */
class b {

    public static void main(String[] args) throws IOException, InterruptedException {
        HttpClient httpClient = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2)
                .connectTimeout(Duration.ofSeconds(20))
                .build();
        HttpRequest httpRequest = HttpRequest.newBuilder()
                .GET()
                .uri(URI.create("http://jiqunar.com:" + 80))
                .build();
        HttpResponse httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        System.out.println(httpResponse.body());
        //assertThat(httpResponse.body()).isEqualTo("Hello from the server!");

    }
}

/*
 *
 * java.util.Collection 接口有一个新的默认方法:toArray 。
 * */
class c {
    public static void main(String[] args) {

        List<String> sampleList = Arrays.asList("Java", "Kotlin");
        String[] sampleArray = sampleList.toArray(String[]::new);
        System.out.println(sampleArray[0]);
        //assertThat(sampleArray).containsExactly("Java", "Kotlin");

    }

}

/*
* Java11从文件中读取/写入文本更加容易。
我们可以使用File类新的的静态方法:readString 和 writeString
* */
class d {
    public static void main(String[] args) throws IOException {
        String tempDir = "D:\study_java\ken\";
        Path filePath = Files.writeString(Files.createTempFile(Path.of(tempDir), "demo", ".txt"), "Sample text");
        System.out.println(filePath.toString());
        String fileContent = Files.readString(filePath);
        System.out.println(fileContent);
        //assertThat(fileContent).isEqualTo("Sample text");

    }
}