Processing Data with Java 8 Stream

Posted: June 8, 2018 in Java8
Tags: , , ,

How can we process really large collections efficiently? Normally we used loops to iterate over a collection.

Lets say we need to iterate over a list of Person object

List<Person> personList = new ArrayList<>();
personList.add(new Person("Sam", 10));
personList.add(new Person("Smith", 9));
personList.add(new Person("Zayn", 2));
personList.add(new Person("Nathan", 1));

Using foreach loop

personList.forEach(person -> {
    System.out.println(" Person Name :: " + person.getName());

In Java 8, we have something new called “Stream”. A stream represents a sequence of elements and supports different kind of operations to perform computations upon those elements.

System.out.println("Traversing List using streams."); -> {

It may seem Java 8’s stream api is a bit verbose than the for-each loop for collections. And we wonder what benefit can come from it.

The difference between for-each loop and using stream api ( in Java 8 is that, we can easily implement parallelism when using the stream api with collection.parallelStream(). Whereas, in for-each loop you will have to handle threads on your own.

/**One of the goals of the stream API in Java8 is to let you break up processing on a system that has multiple CPUs.
 * This multi CPU processing is handled automatically by the Java runtime.
 * All you need to do is turn your sequential stream into a parallel stream.
System.out.println("Traversing List using Parellel streams");
personList.parallelStream().forEach(person -> {


Stream operations are either intermediate or terminal. Intermediate operations return a stream so we can chain multiple intermediate operations without using semicolons. Terminal operations are either void or return a non-stream result. In the above example filter, map and sorted are intermediate operations whereas forEach is a terminal operation. For a full list of all available stream operations see the Stream Javadoc. Such a chain of stream operations as seen in the example below is also known as operation pipeline. 

Predicate<Person> agePredicate = person -> person.getAge() > 5;
System.out.println("Traversing List using Parellel streams and filters");
        .forEach(person -> {

Lets see the different ways of creating stream

Arrays.asList("sam", "smith", "zayn")

Stream.of("sam", "smith", "zayn")
        .ifPresent(s -> System.out.println(s)); int[] {1, 2, 3})

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s