Java Stream 使用

of()接收數組並創建流,然後map()將每個元素都獲取平方,distinct()去重,再使用collect()將流中的元素變成List

@Test
public void mapTest(){
    List<Integer> squaresList = Stream.of(3, 2, 2, 3, 7, 3, 5)
            .map(e -> e*e)
            .distinct()
            .collect(Collectors.toList());
}

Collection可使用stream()獲取流,filter()過濾出空字符串,count()計數

@Test
public void filerTest(){
    List<String> stringList = Arrays.asList("abc", "d", "ef", "ghi", "","123", "bcd","");
    long count = stringList.stream().filter(string -> string.isEmpty()).count();
    // 2
}

filter()過濾出非空字符串,skip()過濾掉前三個,並使用逗號間隔生成String

@Test
public void collectTest(){
    List<String> stringList = Arrays.asList("abc", "d", "ef", "ghi", "","123", "bcd","");
    String mergedString = stringList.stream().filter(string -> !string.isEmpty()).skip(3).collect(Collectors.joining(", "));
    // ghi, 123, bcd
}

一些產生統計結果的收集器也非常有用。
它們主要用於int、double、long等基本類型上,它們可以用來產生類似如下的統計結果。

@Test
public void statTest(){
    List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

    IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();

    System.out.println("列表中最大的數 : " + stats.getMax());//7
    System.out.println("列表中最小的數 : " + stats.getMin());//2
    System.out.println("所有數之和 : " + stats.getSum());//25
    System.out.println("平均數 : " + stats.getAverage());//3.5714285714285716
}

並行執行,順序可能會與原來的順序不同。
filter()過濾出非空字符串,limit()過濾出前兩個

@Test
public void parallelStreamTest(){
    List<String> stringList = Arrays.asList("abc", "d", "ef", "ghi", "","123", "bcd","");
    stringList = stringList.parallelStream().filter(string -> !string.isEmpty()).limit(2).collect(Collectors.toList());
    // [abc, d]
}

合併兩條未關閉的流,如果有個流先使用count(),collect()或forEach(),就會關閉流,那麼合併時會報錯
stream has already been operated upon or closed

@Test
public void concatTest(){
    Stream<Integer> stream1 = Stream.of(1,2,3);
    Stream<Integer> stream2 = Stream.of(4,5,6);

    // 4,5,6,
    Stream.concat(stream1, stream2).filter(e -> e > 3).forEach(e -> System.out.print(e + ","));
}

參考:
Java 8 Stream
Java 之 Stream 流
瞭解Java8中的parallelStream

發佈了69 篇原創文章 · 獲贊 13 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章