JDK11 | Part IV: Enhanced API

I. Introduction

JDK 9 ~ 11 there is a small language in terms of grammar changes, adds considerable number of new API, the new Under this section explains some of the after JDK1.8 API.

Second, enhanced API

Enhanced api 1. collection

Since Java 9, Jdk which is a collection (List / Set / Map) are added and copyOf of methods, which are used to create two immutable collection, use and look at their differences.

/**
 * List的增强api
 */
@Test
public void test1() {
    List<String> list = List.of( "aa", "bb", "cc", "dd" );
    System.out.println( list );

    // 抛出java.lang.UnsupportedOperationException 异常
    list.add( "ee" );

    System.out.println( list );

}

/**
 * Set的增强api
 */
@Test
public void test2() {
    Set<Integer> set1 = Set.of( 100 , 30 ,20 ,15);
    System.out.println(set1);
    // 抛出java.lang.IllegalArgumentException: duplicate element: 20
    Set<Integer> set2 = Set.of( 100 , 30 ,20 ,15 ,20 ,15 );
    // 抛出java.lang.UnsupportedOperationException 异常
    set2.add( 10 );
    System.out.println(set2);
}

/**
 * Map的增强api
 */
@Test
public void test3() {
    Map<String , Integer> map = Map.of("a" , 1 , "b" , 2 , "c" , 3);
    // 抛出java.lang.UnsupportedOperationException 异常
    map.put( "d" , 4 );
    System.out.println(map);
}
复制代码

Use a collection of () method created immutable collection can not add, delete, replace, sorting and other operations, or will be reported java.lang.UnsupportedOperationException exception.

2. Stream enhancement api

Stream is a new feature in the 8 Java, Java 9 began Stream adds the following four new methods.

Increasing the single constructor parameter may be null

@Test
public void test1() {
    long count = Stream.ofNullable( null ).count();
    System.out.println(count);
}
复制代码

DropWhile methods and increase takeWhile

takeWhile: extracting elements from the start of qualifying a collection

@Test
public void test2() {
    List<Integer> res = Stream.of( 1, 2, 3,4, 0, 1 )
            .takeWhile( n -> n < 4 )
            .collect( Collectors.toList() );
    System.out.println(res);
}
复制代码

dropWhile: From the beginning of the collection before removing the qualifying element

@Test
public void test3() {
    List<Integer> res = Stream.of( 1, 2, 3,4, 0, 1 )
            .dropWhile( n -> n < 4 )
            .collect( Collectors.toList() );
    System.out.println(res);
}
复制代码

3. Enhanced string api

Java 11 added a series of string manipulation methods.

@Test
public void test1() {
    //判断字符串是否为空白
    boolean res1 = " ".isBlank();
    //true
    System.out.println(res1);

    //去除首尾空格
    String res2 = " java ~ ".strip();
    // "java ~"
    System.out.println(res2);

    //去除尾部空格
    String res3 = " java ~ ".stripTrailing();
    //" java ~"
    System.out.println(res3);

    //去除首部空格
    String res4 = " java ~ ".stripLeading();
    //"java ~ "
    System.out.println(res4);

    //复制字符串
    String res5 = "java".repeat( 3 );
    // "java"
    System.out.println(res5);

    //行数统计
    long res6 = "A\nB\nC".lines().count();
    //3
    System.out.println(res6);

}
复制代码

4. Optional enhancements api

Opthonal also adds several methods cool, now can easily be converted to an optional time a Stream, or when a null optionally an alternative to it.

@Test
public void test1() {
    //java ~
    String res1 = Optional.of( "java ~" ).orElseThrow();
    System.out.println(res1);

    //1
    long res2 = Optional.of( "java ~" ).stream().count();
    System.out.println(res2);

    //java ~
    Object res3 = Optional.ofNullable( null )
            .or( () -> Optional.of( "java ~" ) )
            .get();
    System.out.println(res3);
}
复制代码

The input stream enhanced api

InputStream finally have a very useful method: transferTo, can be used to transmit data directly to the OutputStream, which is when dealing with the original data stream a very common usage.

@Test
public void test1() {
    try {
        InputStream inputStream = TestInputStream.class.getClassLoader().getResourceAsStream("test.txt");
        var file = new File("/Users/xxx/test2.txt");
        try (var outputStream = new FileOutputStream(file)) {
            inputStream.transferTo(outputStream);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
复制代码

6. HTTP client enhancements api

This is the beginning of the introduction of a Java 9 of handling of HTTP Client API HTTP request, the API supports both synchronous and asynchronous, and already officially available, you can find this API in the java.net package in Java 11.

@Test
public void test1() {
    try {
        var request = HttpRequest.newBuilder()
                .uri( URI.create("http://t.weather.sojson.com/api/weather/city/101020100"))
                .GET()
                .build();

        var client = HttpClient.newHttpClient();

        // 同步
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());

        //异步
        client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
                .thenApply(HttpResponse::body)
                .thenAccept(System.out::println)
                .join();
    } catch (Exception e) {
        e.printStackTrace();

    }
}
复制代码

Welcome scan code or search public micro-channel number "programmer fruit," I am concerned, there is concern surprise ~

Guess you like

Origin juejin.im/post/5cee51e6f265da1ba2524179