Monday, 24 September 2018

Streams in java

Stream (dictionary meaning) : A stream of things is a large number of them occurring one after another.

When i hear about the term stream first thing that comes to mind is 'stream of water' or 'stream of tears ',  which somewhat matches with the above definition. So lets understand with this definition in mind.

Suppose we have a water tank(collection) with water filled in it and we need drinkable water from it. To achieve this we will purify the water. Now to purify we need to put a pipe from tank to purifier and purifier will make sure it purifies and filter the drinkable water and discard the not drinkable water.

Here in the above example Tank is the synonym of Collection(ArrayList, LinkedList, etc..) and the pipe is a way to transform the collection to stream of water which we feed to purifier as input and the purifier checks every input to check if it is fit drinking else discards it. So purifier is basically a filter over the water stream.
Consider this simple example where we are trying to filter even number from the given list


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class HelloWorld{

    public static void main(String []args){
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        List ls = numbers.stream()
                  .filter(n -> n % 2 == 0)
                  .collect(Collectors.toCollection(ArrayList::new));
        ls.stream().forEach(System.out::println);
    }
}

We took a list of 5 numbers and filtered out only even numbers from it. Now this takes little time and practice to digest first, but makes our code neat and compact.

References:

  1. https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html