# How to use terminal stream operations in JShell in Java 9?

JavaObject Oriented ProgrammingProgramming

JShell is an interactive tool that takes simple statements, expressions and etc.. as input, evaluates it, and prints the result immediately to the user.

Terminal Operation is a stream operation that takes a stream as input and doesn't return any output stream. For instance, a terminal operation can be applied to a lambda expression and returns a single result (A single primitive-value/object, or a single collection-of-objects). The reduce(), max(), and min() methods are a couple of such terminal operations.

In the below code snippet, we can use different terminal operations: min(), max(), and reduce() methods in JShell.

## Snippet

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

Published on 23-Apr-2020 17:58:12