Java 8: Streams API

Streams in Java 8 represents a sequence of elements. It supports sequential as well as parallel operations.

The most important thing to know about streams is that it is not a separate Data Structure. It doesn’t store data. It just converts the input data whether it is a List or anything else into a sequence of streams.

They work with Functional Interfaces and Lambda Expressions which makes them so attractive to use.

So how does a stream look like?

import java.util.*;
 
public class MyClass {
 
    public static void main(String[] args) {
        List<String> names = Arrays.asList("David", "John", "Nathan", "Kevin");
 
        names.stream()
                   .map((n) -> n.toUpperCase())
                   .forEach(System.out::println);
    }
}

So here :>

  • We had a list of names initially which can be considered as an Input.
  • Then we convert it into a stream.
  • Then we map and convert it into UpperCase.
  • Finally using the ForEach we loop over the elements and display the names using Sys Out.

Here we had an intermediate operation which was converted to stream and a terminal operation which was forEach.

We can create an empty stream as well. It is done so that we can return a stream with 0 elements instead of null.
Stream s = Stream.empty()

This is how we create an empty stream.

Also we can get a stream eve without using a collection. Like in the above example which is took to display names in UPPER CASE, i took a collection and converted that into a Stream. But we can directly get a Stream as well without using a collection.

We use the Stream.of method here.

Stream streamArray =Stream.of("X","Y","Z");

Parallel Streams:>

You can create Parallel Stream using .parallel() method on Stream object in Java. Parallel Stream is a feature in Java 8 in which multiple cores of the processor will be used. Benefit is efficient processing and execution of data.

public class MyClass {
 
    public static void main(String[] args) {
        int[] array= {1,2,3,4,5};
 
        System.out.println("Use of Parallel Stream");
        IntStream intParallelStream=Arrays.stream(array).parallel();
        intParallelStream.forEach((s)->
        {
            System.out.println(s+" "+Thread.currentThread().getName());
        }
        );
    }
}

So here those 5 elements are getting ran in 5 cores by 5 threads. So accordingly you can see the output.

Parallel streams are used when performance is critical. Else a single serial stream is sufficient.

Hope the article was clear. Thanks for reading.