如何在 Java 9 中的 JShell 中使用终端流操作?

javaobject oriented programmingprogramming更新于 2025/10/23 8:12:17

JShell 是一个 交互式工具,它将简单的语句、表达式等作为输入,对其进行评估,并立即将结果打印给用户。

终端操作 是一种流操作,它将 流作为输入,并且 不返回 任何输出流。例如,终端操作可以应用于 lambda表达式 并返回单个结果(单个 原始值/对象,或单个 对象集合)。 reduce()、ma​​x() 和 min() 方法就是这样的几个终端操作。

在下面的代码片段中,我们可以使用不同的终端操作:JShell 中的 min()、ma​​x() 和 reduce() 方法。

代码片段

jshell> IntStream.range(1, 11).reduce(0, (n1, n2) -> n1 + n2);
$1 ==> 55

jshell> List.of(23, 12, 34, 53).stream().max();
|  Error:
|  method max in interface java.util.stream.Stream cannot be applied to given types;
|    required: java.util.Comparator
|    found: no arguments
|    reason: actual and formal argument lists differ in length
|    List.of(23, 12, 34, 53).stream().max();
|    ^----------------------------------^

jshell> List.of(23, 12, 34, 53).stream().max((n1, n2) -> Integer.compare(n1, n2));
$2 ==> Optional[53]

jshell> $2.isPresent()
$3 ==> true

jshell> List.of(23, 12, 34, 53).stream().max((n1, n2) -> Integer.compare(n1, n2)).get();
$4 ==> 53

jshell> List.of(23, 12, 34, 53).stream().filter(e -> e%2==1).forEach(e -> System.out.println(e))
23
53

jshell> List.of(23, 12, 34, 53).stream().filter(e -> e%2==1).collect(Collectors.toList());
$6 ==> [23, 53]

jshell> List.of(23, 12, 34, 53).stream().min((n1, n2) -> Integer.compare(n1, n2)).get();
$8 ==> 12

相关文章


有用资源