The Java Streams API

  • A stream object plays a similar role to an Iterator.

  • The idea is for a developer to have a sequence (or “pipeline”) of operations, such as map, filter and reduce that can be applied to a collection as a whole.

  • The operations themselves can be expressed using lambda expressions.

  • At the end of the pipeline, the results can be gathered back into another collection.

  • The overall approach would be Collection --> Stream Operation --> ... --> Stream Operation --> Collection

  • Streams operations are not confined to finite data structures and can handle infinite streams. In this situation, instead of using a Collection, we pull elements out of the stream as needed on demand, with lazy evaluation. Operations are only carried out when they are needed.

  • Collections on the other hand use eager evaluation.

Stream Utility Methods

Here are a list of some stream utility methods that are quite useful:

  • Collection::prallelStream

  • List::spliterator and Set::spliterator

  • Map::remove and Map::replace

  • List::sort

  • Map::putIfAbsent and Map::getOrDefault

  • Collection::removeIf

  • Map::computeIfAbsent