Java 8 Stream Terminal Operations

Java 8Object Oriented ProgrammingProgramming

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 = -> 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 = -> 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 = -> a * a * a).forEach(b -> System.out.println(b));

The following program illustrates the use of the collect method.


 Live Demo

import java.util.*;
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 = -> x * x * x).collect(Collectors.toList());


[64, 125, 216, 343]
Published on 03-Jan-2019 15:15:56