函数式编程 - 终端方法
当在流上调用终端方法时,迭代会在流和任何其他链接流上开始。迭代结束后,将返回终端方法的结果。终端方法不返回 Stream,因此一旦通过流调用终端方法,则其非终端方法或中间方法的链接就会停止/终止。
通常,终端方法返回单个值并在流的每个元素上调用。以下是Stream接口的一些重要的终端方法。每个终端函数都采用谓词函数,启动元素的迭代,将谓词应用于每个元素。
anyMatch - 如果谓词对任何元素返回 true,则它返回 true。如果没有元素匹配,则返回 false。
allMatch - 如果谓词对任何元素返回 false,则返回 false。如果所有元素都匹配,则返回 true。
noneMatch - 如果没有元素匹配,则返回 true,否则返回 false。
collect - 每个元素都存储到传递的集合中。
count - 返回通过中间方法传递的元素的计数。
findAny - 返回包含任何元素的可选实例或返回空实例。
findFirst - 返回可选实例下的第一个元素。对于空流,返回空实例。
forEach - 对每个元素应用消费者函数。用于打印流的所有元素。
min - 返回流的最小元素。根据传递的比较器谓词比较元素。
max - 返回流的最大元素。根据传递的比较器谓词比较元素。
reduce - 使用传递的谓词将所有元素减少为单个元素。
toArray - 返回流元素的数组。
示例 - 终端方法
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FunctionTester {
public static void main(String[] args) {
List<String> stringList
= Arrays.asList("One", "Two", "Three", "Four", "Five", "One");
System.out.println("Example - anyMatch\n");
//anyMatch - check if Two is present?
System.out.println("Two is present: "
+ stringList
.stream()
.anyMatch(s -> {return s.contains("Two");}));
System.out.println("\nExample - allMatch\n");
//allMatch - check if length of each string is greater than 2.
System.out.println("Length > 2: "
+ stringList
.stream()
.allMatch(s -> {return s.length() > 2;}));
System.out.println("\nExample - noneMatch\n");
//noneMatch - check if length of each string is greater than 6.
System.out.println("Length > 6: "
+ stringList
.stream()
.noneMatch(s -> {return s.length() > 6;}));
System.out.println("\nExample - collect\n");
System.out.println("List: "
+ stringList
.stream()
.filter(s -> {return s.length() > 3;})
.collect(Collectors.toList()));
System.out.println("\nExample - count\n");
System.out.println("Count: "
+ stringList
.stream()
.filter(s -> {return s.length() > 3;})
.count());
System.out.println("\nExample - findAny\n");
System.out.println("findAny: "
+ stringList
.stream()
.findAny().get());
System.out.println("\nExample - findFirst\n");
System.out.println("findFirst: "
+ stringList
.stream()
.findFirst().get());
System.out.println("\nExample - forEach\n");
stringList
.stream()
.forEach(System.out::println);
System.out.println("\nExample - min\n");
System.out.println("min: "
+ stringList
.stream()
.min((s1, s2) -> { return s1.compareTo(s2);}));
System.out.println("\nExample - max\n");
System.out.println("min: "
+ stringList
.stream()
.max((s1, s2) -> { return s1.compareTo(s2);}));
System.out.println("\nExample - reduce\n");
System.out.println("reduced: "
+ stringList
.stream()
.reduce((s1, s2) -> { return s1 + ", "+ s2;})
.get());
}
}
输出
Example - anyMatch Two is present: true Example - allMatch Length > 2: true Example - noneMatch Length > 6: true Example - collect List: [Three, Four, Five] Example - count Count: 3 Example - findAny findAny: One Example - findFirst findFirst: One Example - forEach One Two Three Four Five One Example - min min: Optional[Five] Example - max min: Optional[Two] Example - reduce reduced: One, Two, Three, Four, Five, One