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

 Live Demo

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]
Updated on: 2020-06-26T15:38:20+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements