JavaRush /Java Blog /Random-TW /串流媒體介面

串流媒體介面

在 Random-TW 群組發布
流 API - 1

什麼是流 API?

Stream API 是一種以函數式風格處理資料結構的新方法。Stream API(一個電腦程式與另一個程式通訊的方式的描述)的核心是資料流。一般來說,「線程」這個術語本身在程式設計中,特別是在 Java 中是相當模糊的。
流 API - 1
隨著 Java 8 的出現,Stream API 允許程式設計師編寫更簡短的程式碼,即簡化資料集的處理,特別是簡化過濾、排序和其他資料操作操作。如果沒有中間操作,則可以而且應該經常不使用流,否則程式碼會比不使用流更複雜。
流 API - 2
我到底該從哪裡開始呢?從建立 Stream 實例開始,該實例基於我們需要的集合、陣列或方法以及相應的資料來源:
List<String> list = new ArrayList<String>();
       list.add("One");
       list.add("Two");
       list.add("Three");
       list.add("Four");
       list.add("Five");
       list.add("Six");
       list.add("Seven");
       list.add("Eight");
       list.add("Nine");
       list.add("Ten");
       Stream stream = list.stream();
如上所述,Stream API 允許您減少程式碼行數。流的範例:
IntStream.of(50, 60, 70, 80, 90, 100, 110, 120).filter(x -> x < 90).map(x -> x + 10)
.limit(3).forEach(System.out::print);
沒有線程的範例:
int[] arr = {50, 60, 70, 80, 90, 100, 110, 120
	int count = 0;
	for (int x : arr) {
	    if (x >= 90) continue;
	    x += 10;
	    count++;
	    if (count > 3) break;
	    System.out.print(x);
	}
建立 Stream 的可能方法:
流 API - 3
  • 空流:Stream.empty()
  • 來自清單的串流:list.stream()
  • 從地圖流:map.entrySet().stream()
  • 來自數組的流:Arrays.stream(array)
  • 來自指定元素的流:Stream.of("1", "2", "3")
接下來是運算子(本質上是 Stream 類別的方法),運算子可以分為兩類:
  • 中間(也稱為“惰性”)- 處理傳入元素並返回流。元素處理鏈中可以有許多中間運算子。
  • 終端機(“terminal”,也稱為“eager”)-處理元素並終止流,因此鏈中只能有一個終端運算子。
例子:
1.List<String> list = new ArrayList<String>();
2.list.add("One");11.list.add("Ten");
12.Stream stream = list.stream();
13.stream.filter(x-> x.toString().length() == 3).forEach(System.out::println);
這裡發生了什麼事:
  • 1 - 建立一個清單list
  • 2-11-填寫測試數據;
  • 12-創建一個物件Stream
  • 13 - 方法filter(過濾器) - 中間運算符,x相當於枚舉集合中的一個元素(與 一樣for each),之後-> 我們指示如何過濾我們的集合,並且由於這是一個中間運算符,因此過濾後的集合進一步到方法,forEach它又是枚舉的終端(最終)類似物for each(表達式System.out::println縮寫為:,x-> System.out.println(x))它依次遍歷傳遞給它的集合的所有元素並顯示它)
流 API - 5
要點:
  • 在呼叫終端操作員之前,處理不會開始。list.stream().filter(s -> s > 5)(不會從清單中取出單一元素);
  • 流的實例不能多次使用 =( ;
  • 流 API - 6

    因此,每次新的時候:

    list.stream().filter(x-> x.toString().length() == 3).forEach(System.out::println);
    list.stream().forEach(x -> System.out.println(x));
  • 一個流上可以呼叫多個中間運算符,而只有一個終端運算符:

    stream.filter(x-> x.toString().length() == 3).map(x -> x + " - the length of the letters is three").forEach(x -> System.out.println(x));
接下來,我們來看一些中間運算子:
流 API - 7
  • filter(Predicate predicate)過濾流,僅傳遞那些通過條件的元素(Predicate 是 Java SE 8 中添加到包中的內建函數介面。檢查“ true ”和“ falsejava.util.function的值);
  • map(Function mapper)使我們可以創建一個函數,用它來更改每個元素並進一步跳過它(函數介面Function<T,R>表示從 T 類型的物件到 R 類型的物件的轉換函數)
  • flatMap(Function<T, Stream<R>> mapper)- 與 的情況一樣map,它們用於轉換為原始流。
例如,當使用一組流(數組、列表等)時,它將它們轉換為一個流(數組、列表等) [stream1,stream2,stream3,stream4] => stream
String[] array = {"Java", "Ruuuuussshhh"};
Stream<String> streamOfArray = Arrays.stream(array);
streamOfArray.map(s->s.split("")) //Convert the word to an array of letters
        .flatMap(Arrays::stream).distinct() //aligns each generated thread into a single thread
        .collect(Collectors.toList()).forEach(System.out::println);
map它轉換為線程列表(更準確地說<Stream>是線程)時[stream1,stream2,stream3,stream4] =>Stream.of(stream1,stream2,stream3,stream4)
String[] array = {"Java", "Ruuuuussshhh"};
Stream<String> streamOfArray = Arrays.stream(array);
streamOfArray.map(s->s.split("")) //Convert the word to an array of letters
        .map(Arrays::stream).distinct() //Make the array into a separate thread
        .collect(Collectors.toList()).forEach(System.out::println);
與 相比的另一個區別是map,您可以將一個元素轉換為零、一個或多個其他元素。為了將一個元素轉換為零個元素,您需要返回null, 或一個空流。要轉換為一個元素,您需要從一個元素傳回一個流,例如 via Stream.of(x)。若要傳回多個元素,您可以透過任何方式使用這些元素建立一個流。相同的 flatMap 方法,但對於 Double、Integer 和 Long:
  • flatMapToDouble(函數映射器)
  • flatMapToInt(函數映射器)
  • flatMapToLong(函數映射器)
另一個比較的例子,flatMap:
Stream.of(2, 3, 0, 1, 3)
        .flatMapToInt(x -> IntStream.range(0, x))
        .forEach(System.out::print);// 010120012
  • IntStream.range(0,x) – 將 0(含)到 x(不含)的元素輸出到流;

    地圖:

    Stream.of(2, 3, 0, 1, 3)
            .map(x -> IntStream.range(0, x))
            .forEach(System.out::print);//list of streams (streams);
  • limit(long maxSize) – 依元素數量限制流:

    stream.limit(5).forEach(x -> System.out.println(x));
  • Skip(long n) – 跳過 n 個元素:

    stream.skip(3).forEach(x -> System.out.println(x));
  • 排序()

  • sorted(Comparator comparator) – 對流進行排序(像 TreeMap 一樣排序):

    stream.sorted().forEach(x -> System.out.println(x));
  • unique() — 檢查流中元素的唯一性(刪除元素的重複);

  • dropWhile(Predicate predicate) - 跳過滿足條件的元素(出現在 java 9 中,Predicate<T> 函數介面檢查是否滿足某個條件。如果滿足,則傳回 true。lambda 表達式採用類型的物件T 作為參數:

    Predicate<Integer> isPositive = x -> x > 0;
           System.out.println(isPositive.test(3)); // true
           System.out.println(isPositive.test(-9)); // false
碼頭營運商:
流 API - 8
  • forEach(Consumer action) – 類似於 foreach(Consumer<T> 對類型 T 的物件執行某些操作而不回傳任何內容);

  • count() – 傳回流元素的數量:

    System.out.println(stream.count());

  • collect(Collector Collector) – 方法將所有元素收集到列表、集合或其他集合中,根據某種標準對元素進行分組,將所有元素組合成字串等:

    List<String> list = Stream.of(One,Two,Three).collect(Collectors.toList());
  • collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner)— 與 相同,collect(collector)只是為了方便而對參數進行了分解(supplier提供新的物件(容器),例如new ArrayList()accumulator在容器中添加一個元素,combiner將流的各個部分組合在一起);

  • reduce(T Identity, BinaryOperator Accumulator) - 將流的所有元素轉換為一個物件(計算所有元素的總和,或找到最小元素),首先取出該物件identity和流的第一個元素,應用函數accumulatoridentity成為它的結果。然後剩下的元素一切繼續。

    int sum = Stream.of(1, 2, 3, 4, 5).reduce(10, (acc, x) -> acc + x);// = 25
  • reduce(BinaryOperator accumulator)— 與上面相同的方法,但缺少第一個元素identity,它是流的第一個元素

    Optional min(Comparator comparator)
    可選 max(Comparator comparator) 根據傳入的比較器搜尋最小/最大元素;

  • findFirst()– 取出流的第一個元素:

    Stream.of(1, 2, 3, 4, 9).findFirst();
  • allMatch(Predicate predicate)—如果流的所有元素都符合條件,則傳回true 。如果遇到呼叫謂詞函數的結果為false 的任何元素,則運算子停止掃描元素並傳回false

    Stream.of(1, 2, 3, 4, 9).allMatch(x -> x <= 7);//false
  • anyMatch(Predicate predicate)—如果流中至少有一個元素符合條件,則傳回truepredicate

    Stream.of(1, 2, 3, 4, 9).anyMatch(x -> x >= 7);//true
  • noneMatch(Predicate predicate)—如果遍歷完流的所有元素後,沒有一個元素滿足條件,則傳回truepredicate

    Stream.of(1, 2, 3, 4, 9).noneMatch(x -> x >= 7);//false
最後我想看看一些方法Collectors
  • toList()— 將元素收集到List

    List<Integer> list = Stream.of(99, 2, 3).collect(Collectors.toList());
  • toSet()— 將元素收集到一個集合中:

    Set<Integer> set = Stream.of(99, 2, 3).collect(Collectors.toSet());
  • counting()— 計算元素數量:

    Long count = Stream.of("1", "2", "3", "4").collect(Collectors.counting());
  • joining()

  • joining(CharSequence delimiter)

  • joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)— 將元素收集到一行中。此外,您可以指定分隔符號以及整個序列的前綴和後綴:

    String a = Stream.of("s", "u" ,"p", "e", "r").collect(Collectors.joining());
           System.out.println(a); // super
    
           String b = Stream.of("s", "u", "p", "e", "r").collect(Collectors.joining("-"));
           System.out.println(b); // s-u-p-e-r
    
           String c = Stream.of("s", "u", "p", "e", "r").collect(Collectors.joining(" -> ", "[ ", " ]"));
           System.out.println(c);  // [ s -> u -> p -> e -> r ]
  • summingInt(ToIntFunction mapper)

  • summingLong(ToLongFunction mapper)

  • summingDouble(ToDoubleFunction mapper)- 將物件轉換為 int/long/double 並計算總和的收集器。

有用的連結: PS:不要羞於按讚^ : ^
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION