- 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]
Advertisements
To Continue Learning Please Login
Login with Google