Java Stream

Java Stream

Java Stream API has been introduced in Java 8 which majorly focuses on providing various method for operation on Source.  It operates around Source as wrapper making bulk operation fast and in few lines.

Stream bring functional programming to Java and heavily uses lambda expression for its implementation. ParallelStream can be used for multi-threaded operations.

Stream operations can be classified into two sets

  1. Intermediate Operations
  2. Terminal Operations

Intermediate Operations:

Intermediate Operations will return Stream after completing its operation. We can say it as it converts from one stream to another stream after operating on it. This enables operations to be chained together. As an example, we have List of Strings as Source and we want apply filter and sort operations on it. It can be chained as below

If you notice that we cannot add any other operation after forEach which is an Terminal operation, so terminal operation has to be applied only end of pipeline.

Here is list of Intermediate Operations provided by Stream

  1. map(),
  2. filter(),
  3. distinct(),
  4. sorted(),
  5. limit(),
  6. skip()

Terminal Operations:

Terminal operation will return non stream values which can be primitive, object, collection or may not return anything. This restrict operations to be pipelined. Hence it is used for end result only.

Here is the list of all Stream terminal operations:

  1. toArray()
  2. collect()
  3. count()
  4. reduce()
  5. forEach()
  6. forEachOrdered()
  7. min()
  8. max()
  9. anyMatch()
  10. allMatch()
  11. noneMatch()
  12. findAny()
  13. findFirst()

Leave a Reply

Your email address will not be published. Required fields are marked *