How to use Streams API

Subscribe to my newsletter and never miss my upcoming articles

Java 8 introduced us with Streams. Streams represents a sequence of objects from a source.

Streams provide number of APIs for aggregate operation. Streams take arrays, collections or i/o sources for input.

Two types of Stream operations:

  • Intermediate operations return streams for further processing.
  • Terminal operations return either void or non-stream results.
List<String> myList =
    Arrays.asList("test1", "sameresult", "netresult", "grossprofit", "test2");

myList
    .stream()
    .filter(s -> s.startsWith("test"))
    .map(String::toUpperCase)
    .sorted()
    .forEach(System.out::println);

As shown above, filter, map, sorted are intermediate operations and forEach is a terminal operation.

One thing to note about terminal operations is that once you call terminal operations on stream, you can not reuse the stream.

While using streams, you can use various operations like reduce, filter, collect, map, forEach etc.

There are more operations that you can use with streams, Java Docs provide the list of operations.

Thank you for reading my post. Follow me on twitter at betterjavacode

No Comments Yet