中间方法
Java 8 中引入了 Stream API,以方便 Java 中的函数式编程。Stream API 的目标是以功能方式处理对象集合。根据定义,Stream 是一个可以对其元素进行内部迭代的 Java 组件。
Stream 接口具有终端方法和非终端方法。非终端方法是向流添加侦听器的操作。当调用流的终端方法时,流元素的内部迭代开始,并且为每个元素调用附加到流的侦听器,并由终端方法收集结果。
这种非终端方法称为中间方法。中间方法只能通过调用终端方法来调用。以下是Stream接口的一些重要的中间方法。
filter - 根据给定标准从流中过滤掉不需要的元素。此方法接受谓词并将其应用于每个元素。如果谓词函数返回 true,则元素包含在返回的流中。
map - 根据给定标准将流的每个元素映射到另一个项目。此方法接受一个函数并将其应用于每个元素。例如,将流中的每个 String 元素转换为大写 String 元素。
flatMap - 此方法可用于根据给定条件将流的每个元素映射到多个项目。当需要将复杂对象分解为简单对象时,使用此方法。例如,将句子列表转换为单词列表。
unique - 如果存在重复项,则返回唯一元素流。
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