JDK11 | 第四篇 : 加強API

1、簡介

JDK 9~11 在語言語法方面有一個小改動,增長了至關數量的新API,這一節講解下JDK1.8以後新增的一些API。java

2、加強API

1. 集合的加強api

自Java 9開始,Jdk裏面爲集合(List / Set / Map)都添加了of和copyOf方法,它們兩個都用來建立不可變的集合,來看下它們的使用和區別。程序員

/** * 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);
}
複製代碼

使用of()方法建立的集合,爲不可變集合,不能進行添加、刪除、替換、排序等操做,否則會報 java.lang.UnsupportedOperationException 異常。es6

2. Stream的加強api

Stream 是 Java 8 中的新特性,Java 9 開始對 Stream 增長了如下 4 個新方法。json

增長單個參數構造方法,可爲null

@Test
public void test1() {
    long count = Stream.ofNullable( null ).count();
    System.out.println(count);
}
複製代碼

增長 takeWhile 和 dropWhile 方法

takeWhile:從集合開頭提取符合條件的元素api

@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:從集合開頭移除前符合條件的元素微信

@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. 字符串加強api

Java 11增長了一系列的字符串處理方法。異步

@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加強api

Opthonal也增長了幾個很是酷的方法,如今能夠很方便的將一個可選轉換成一個Stream,或者當一個空可選時給它一個替代的。ui

@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);
}
複製代碼

5. 輸入流加強api

InputStream終於有了一個很是有用的方法:transferTo,能夠用來將數據直接傳輸到OutputStream,這是在處理原始數據流時很是常見的一種用法。es5

@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客戶端加強api

這是Java 9開始引入的一個處理HTTP請求的的化化HTTP Client API,該API支持同步和異步,而在Java 11中已經爲正式可用狀態,你能夠在java.net包中找到這個API。spa

@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();

    }
}
複製代碼

歡迎掃碼或微信搜索公衆號《程序員果果》關注我,關注有驚喜~

相關文章
相關標籤/搜索