Home  >  Article  >  Java  >  The difference between intermediate operations and terminal operations in Java 8

The difference between intermediate operations and terminal operations in Java 8

王林
王林forward
2023-08-19 20:37:15681browse

Java 8中中间操作和终端操作的区别

Stream was introduced in Java 8 and it is only used to process a set of data and not to sort the elements. It does not modify the actual collection, they only provide results according to the pipeline method.

The Stream API supports multiple operations, which are divided into two parts:

  • Intermediate Operation- These operations are used to pipe other methods and convert to other streams. They produce no results because these operations are not called until the terminal operation is performed. Here is an example:
  • sorted(Comparator8742468051c85b06f0a0af9e3e506b5c)
  • peek(Consumer8742468051c85b06f0a0af9e3e506b5c)
  • distinct()
  • Terminal operations - These operations used to generate results. They cannot be used to chain other methods. Here is an example:
  • forEach
  • count
  • toArray
##1Basic Operations These operations are used to pipe other methods and convert to other streams Terminal operations in Java are the last step methods applied to a stream . 2Return TypeThey just return another flow. They return the final result. 3Methodsorted(Comparator8742468051c85b06f0a0af9e3e506b5c )##4.Examples of Intermediate and Terminal operations
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);
      });
   }
}
serial number Keywords Intermediate Operations Terminal Operations

peek(Consumer8742468051c85b06f0a0af9e3e506b5c)

distinct()

##forEach

count

toArray

Use Case

These operations should be used to transform a stream into another stream

They can be used to generate results.

The above is the detailed content of The difference between intermediate operations and terminal operations in Java 8. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete