中間方法
Stream API 在 Java 8 中引入,旨在促進 Java 中的函數語言程式設計。Stream API 針對以函式式方式處理物件集合。根據定義,Stream 是一個 Java 元件,可以對其元素進行內部迭代。
Stream 介面具有終止方法和非終止方法。非終止方法是指向流新增監聽器的操作。當呼叫流的終止方法時,流元素的內部迭代開始,並且附加到流的監聽器將為每個元素呼叫,結果由終止方法收集。
此類非終止方法稱為中間方法。中間方法只能透過呼叫終止方法來呼叫。以下是 Stream 介面的一些重要的中間方法。
filter − 根據給定條件從流中過濾掉不需要的元素。此方法接受一個謂詞並將其應用於每個元素。如果謂詞函式返回 true,則元素包含在返回的流中。
map − 根據給定條件將流的每個元素對映到另一個專案。此方法接受一個函式並將其應用於每個元素。例如,將流中每個字串元素轉換為大寫字串元素。
flatMap − 此方法可用於根據給定條件將流的每個元素對映到多個專案。當需要將複雜物件分解為簡單物件時,使用此方法。例如,將句子列表轉換為單詞列表。
distinct − 如果存在重複項,則返回唯一元素的流。
limit − 返回一個元素有限的流,其中限制透過將數字傳遞給 limit 方法來指定。
示例 - 中間方法
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class FunctionTester {
public static void main(String[] args) {
List<String> stringList =
Arrays.asList("One", "Two", "Three", "Four", "Five", "One");
System.out.println("Example - Filter\n");
//Filter strings whose length are greater than 3.
Stream<String> longStrings = stringList
.stream()
.filter( s -> {return s.length() > 3; });
//print strings
longStrings.forEach(System.out::println);
System.out.println("\nExample - Map\n");
//map strings to UPPER case and print
stringList
.stream()
.map( s -> s.toUpperCase())
.forEach(System.out::println);
List<String> sentenceList
= Arrays.asList("I am Mahesh.", "I love Java 8 Streams.");
System.out.println("\nExample - flatMap\n");
//map strings to UPPER case and print
sentenceList
.stream()
.flatMap( s -> { return (Stream<String>)
Arrays.asList(s.split(" ")).stream(); })
.forEach(System.out::println);
System.out.println("\nExample - distinct\n");
//map strings to UPPER case and print
stringList
.stream()
.distinct()
.forEach(System.out::println);
System.out.println("\nExample - limit\n");
//map strings to UPPER case and print
stringList
.stream()
.limit(2)
.forEach(System.out::println);
}
}
輸出
Example - Filter Three Four Five Example - Map ONE TWO THREE FOUR FIVE ONE Example - flatMap I am Mahesh. I love Java 8 Streams. Example - distinct One Two Three Four Five Example - limit One Two
廣告