- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java 8 Stream Terminal Operations
Streams in Java have a few terminal operations. They are as follows −
collect − The collect method returns the outcome of the intermediate operations
List id = Arrays.asList(“Classes","Methods","Members"); List output = id.stream().filter(s -> s.startsWith("M")).collect(Collectors.toList());
reduce − The reduce method is reduces the elements of a stream into a single element having a certain value after computation. The BinaryOperator is an argument of the reduce method.
List list1 = Arrays.asList(11,33,44,21); int even = list1.stream().filter(x -> x % == 0).reduce(0,(ans,i) -> ans+i);
forEach − This method iterates through every element in the stream
List list1= Arrays.asList(1,3,5,7); List finalList = list1.stream().map(a -> a * a * a).forEach(b -> System.out.println(b));
The following program illustrates the use of the collect method.
Example
import java.util.*; import java.util.stream.*; public class Example { public static void main(String args[]) { List<Integer> list1 = Arrays.asList(4,5,6,7); //creating an integer list // collect method List<Integer> answer = list1.stream().map(x -> x * x * x).collect(Collectors.toList()); System.out.println(answer); } }
Output
[64, 125, 216, 343]
- Related Articles
- How to use terminal stream operations in JShell in Java 9?
- Difference between intermediate and terminal operations in Java 8
- Java 8 Streams and its operations
- How to use intermediate stream operations in JShell in Java 9?
- How to Convert a Java 8 Stream to an Array?
- Program to Iterate over a Stream with Indices in Java 8
- Stream In Java
- Character Stream vs Byte Stream in Java\n
- Stream sorted() in Java
- Java Stream Collectors toCollection() in Java
- Array To Stream in Java
- Java Stream findAny() with examples
- Difference between the byte stream and character stream classes in Java?
- Database operations in Java
- Convert Stream to Set in Java

Advertisements