Difference between intermediate and terminal operations in Java 8


Stream is introduced in Java 8, it is only used for processing group of data not for the storting elements.. It does not modify the actual collection, they only provide the result as per the pipelined methods.

Stream api supports multiple operations and operations are divided into two parts −

  • Intermediate Operation- These operations are used to pipeline other methods and to transform into the other streams. They don’t produce results because these operation does not invoke until the terminal operation gets executed. Below are the examples −
  • sorted(Comparator<T>)
  • peek(Consumer<T>)
  • distinct()
  • Terminal operations - These operations are used to produce results. They can’t be used for chaining the other methods. Below are the examples −
  • forEach
  • count
  • toArray
Sr. No.KeyIntermediate OperationsTerminal Operations
1
Basic
These operations are used to pipeline other methods and to transform into the other streams
A terminal operation in Java is a method applied to a stream as the final step.
2
Return Type
They only return another stream.
They return final result.
3
Method
sorted(Comparator<T>)
peek(Consumer<T>)
distinct()
forEach
count
toArray


4.
Use Case
These operations should be used to transform stream into another stream
They can be used to produce results.

Example of Intermediate and Terminal Operation

public class Main {
   public static void main(String args[]) throws InterruptedException, ExecutionException {
      List<String> laptopList = new ArrayList();
      laptopList.add("DELL");
      laptopList.add("ACER");
      laptopList.add("HCL");

      // Intermediate operation
      laptopList.sort((p1, p2) -> p1.compareTo(p2));

      // Terminal Operation
      laptopList.forEach(a -> {
         System.out.println(a);
      });
   }
}

Updated on: 09-Sep-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements