Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách dùng terminal stream operation trong JShell Java 9?

JShell là interactive tool nhận câu lệnh đơn giản, biểu thức... làm input, đánh giá và in kết quả ngay cho người dùng.

Terminal Operation là stream operation nhận stream làm input và không trả về output stream. Ví dụ, terminal operation áp dụng cho lambda expression trả về kết quả đơn (một primitive-value/object, hoặc một collection-of-objects). Phương thức reduce(), max(), min() là một vài terminal operation như vậy.

Đoạn mã dưới dùng các terminal operation khác nhau: min(), max(), reduce() trong JShell.

Đoạn mã

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
|   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