

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use terminal stream operations in JShell in Java 9?
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
- Related Questions & Answers
- How to use intermediate stream operations in JShell in Java 9?
- Java 8 Stream Terminal Operations
- JShell in Java 9?
- How to debug JShell in Java 9?
- How to use the collect() method in Stream API in Java 9?
- How to get JShell documentation in Java 9?
- When to use the ofNullable() method of Stream in Java 9?
- How to create JShell instance programmatically in Java 9?
- How to reset the JShell session in Java 9?
- How to implement java.time.LocalDate using JShell in Java 9?
- How to implement JShell using JavaFX in Java 9?
- How JShell tool works internally in Java 9?
- How to import external libraries in JShell in Java 9?
- How to handle an exception in JShell in Java 9?
- How to create scratch variables in JShell in Java 9?
Advertisements