Streams in java 8

A Stream is a sequence of elements supporting sequential and parallel aggregate operations. Streams have been introduced to Java starting from version 8.

Example of the use of Streams

Consider the following example:

// create a collection of Products
List<Product> products= new ArrayList<Product>();

// calculate the sum of prices of the products whose 
// made locally
// and the price is greater or equal to 10
int sumOfPrices = products.stream()
                      .filter(p -> p.isMadeLocally() == true)
                      .filter(p -> p.getPrice() >=10 )
                      .mapToInt(p -> p.getPrice())
                      .sum();

In the above example we create a stream of products using products.stream() .  Then we filter the products by using the filter() function that takes an object of type Predicate as parameter (in other words, a Functional Interface), meaning that we can use a Lamba expression like in this example.

The mapToInt() function takes a parameter of type ToIntFunction which is also a functional interface, this is why we used the lambda expression p-> p.getPrice() . The mapToInt() function returns an object of type IntStream . And finally the sum() function calculates the sum of all the prices of the products.

Convert a Collection into Stream and vice-versa

filter() functions are sometimes combined with collect() function that converts a stream into a Collection. Example :

// In this example, the products List is converted to a stream, and then to a List
List<Product> listOfProducts = products.stream().filter(p-> p.getPrice()>10).collect(Collectors.toList());

 

Streams Vs Collections

Streams and Collections seem to be similar, but in reality they have different goals: Collections are mainly concerned with the efficient management of, and access to, their elements. However Streams do not give a direct access to their elements or manipulate them, but are instead concerned with declaratively describing their source and the computational operations which will be performed in aggregate on that source.

The BaseStream.iterator() and BaseStream.spliterator() operations can be used to perform a controlled traversal.

Sequential and parallel streams

Stream pipelines can be sequential or parallel. Using the Collection.stream() function will create a sequential stream, and the use of Collection.parallelStream() will create a stream with a parallel mode of execution.

 

You like this content ? Share it with you entourage !

Leave a Reply

Your email address will not be published.