Java Streams Code Snippets

What is a Java Stream?

Java Stream is a sequence of elements supporting the sequential and parallel aggregate operation. This example shows an aggregate operation using Stream and IntStream

int sum = widgets.stream()
                 .filter(w -> w.getColor() == RED)
                 .mapToInt(w -> w.getWeight())
                 .sum();

In this example (from Oracle Stream doc), widgets is a Collection<Widget>. A stream of Widget objects was created via Collection.stream(), filter it to product a stream containing only the red widgets, and then transform it into a stream of int values representing the weight of each red widget. Finally this stream is summed to produce a total weight.

 

This post lists Java Streams code snippets that I find very useful