函数式编程 - 终端方法
当在流上调用终端方法时,迭代将在流和任何其他链接流上开始。迭代结束后,将返回终端方法的结果。终端方法不返回流,因此一旦在流上调用终端方法,其非终端方法或中间方法的链接就会停止/终止。
通常,终端方法返回单个值,并在流的每个元素上调用。以下是 Stream 接口的一些重要终端方法。每个终端函数都采用谓词函数,启动元素的迭代,并将谓词应用于每个元素。
anyMatch − 如果谓词对任何元素返回 true,则返回 true。如果没有元素匹配,则返回 false。
allMatch −如果谓词对任何元素返回 false,则返回 false。如果所有元素都匹配,则返回 true。
noneMatch − 如果没有元素匹配,则返回 true,否则返回 false。
collect − 将每个元素存储到传递的集合中。
count − 返回通过中间方法传递的元素数量。
findAny − 返回包含任何元素的 Optional 实例,否则返回空实例。
findFirst − 返回 Optional 实例下的第一个元素。对于空流,返回空实例。
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"); //anyMatch-检查是否存在 Two? System.out.println("Two is present: " + stringList .stream() .anyMatch(s -> {return s.contains("Two");})); System.out.println("Example - allMatch"); //allMatch - 检查每个字符串的长度是否大于 2。 System.out.println("Length > 2: " + stringList .stream() .allMatch(s -> {return s.length() > 2;})); System.out.println("Example - noneMatch"); //noneMatch - 检查每个字符串的长度是否大于 6。 System.out.println("Length > 6: " + stringList .stream() .noneMatch(s -> {return s.length() > 6;})); System.out.println("Example - collect"); System.out.println("List: " + stringList .stream() .filter(s -> {return s.length() > 3;}) .collect(Collectors.toList())); System.out.println("Example - count"); System.out.println("Count: " + stringList .stream() .filter(s -> {return s.length() > 3;}) .count()); System.out.println("Example - findAny"); System.out.println("findAny: " + stringList .stream() .findAny().get()); System.out.println("Example - findFirst"); System.out.println("findFirst: " + stringList .stream() .findFirst().get()); System.out.println("Example - forEach"); stringList .stream() .forEach(System.out::println); System.out.println("Example - min"); System.out.println("min: " + stringList .stream() .min((s1, s2) -> { return s1.compareTo(s2);})); System.out.println("Example - max"); System.out.println("min: " + stringList .stream() .max((s1, s2) -> { return s1.compareTo(s2);})); System.out.println("Example - reduce"); 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