Sobes.tech
Senior

What types of operations are available in streams (Stream API)?

sobes.tech AI

Answer from AI

The Stream API in Java supports several types of operations, which can be divided into intermediate and terminal operations.

Intermediate operations return a new Stream and allow chaining of data processing:

  • filter — filtering elements based on a condition
  • map — transforming elements
  • flatMap — transforming and "flattening" nested structures
  • distinct — removing duplicates
  • sorted — sorting elements
  • limit — limiting the number of elements
  • skip — skipping the first N elements

Terminal operations complete the processing and return a result:

  • forEach — performing an action for each element
  • collect — collecting elements into a collection or other structure
  • reduce — reducing elements into a single value
  • count — counting the number of elements
  • anyMatch, allMatch, noneMatch — checking conditions
  • findFirst, findAny — finding elements

Intermediate operations are lazy and are only executed when a terminal operation is invoked.