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


JShell 是一種互動式工具,接受簡單的語句、表示式等作為輸入,對其求值,並立即向用戶列印結果。

終端操作是一種流操作,接受流作為輸入不返回任何輸出流。例如,可以將終端操作應用於lambda 表示式,並返回一個結果(單個基元值/物件,或單個物件集合)。reduce()max()min() 方法就是此類終端操作。

在下面的程式碼片段中,我們可以在 JShell 中使用不同的終端操作:min()max()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

更新於: 23-Apr-2020

201 次訪問

開啟您的職業

完成課程以獲得認證

立即開始
廣告