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

The difference between intermediate operations and terminal operations in Java 8

王林
Release: 2023-08-19 20:37:15
forward
704 people have browsed it

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(Comparator)
  • peek(Consumer)
  • 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(Comparator )##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);
      });
   }
}
Copy after login
serial number Keywords Intermediate Operations Terminal Operations

peek(Consumer)

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template