Introduction to Java Streams API

What is Java Streams API?

Streams API is another major feature introduced as part of Java 8.
The main purpose of Streams in Java is to perform operations on data structures (arrays, lists, sets, maps, etc.).
Classes that are part of the Streams API are located inside the java.util.stream package.

The Stream represents a pipeline of methods performed on a data structure.

It is important to note that the Stream does not modify the data structure or store the elements. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection.


How to work with Streams in Java?

First, we need to create a Stream, then perform some intermediate operations to transform it into another Stream.

After that, we need to perform a terminal operation on the final Stream to get the result.

A Stream pipeline consists of a source (list, array …) followed by zero or more intermediate operations such as Stream.filter() or Stream.map(), and a terminal operation such as Stream.forEach() or Stream.reduce().


Let’s see a few examples:

Example 1:
A program that takes an array of integers, filters only even numbers, multiplies them by 2, and prints them as a result.

class Test {

  public static void main(String[] args) {
    int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    Arrays.stream(array) // Creating the stream for array
            .filter(number -> number % 2 == 0)  // intermediate operation
            .map(number -> number * 2)  // intermediate operation
            .forEach(num -> System.out.print(num + " "));  // terminal operation
  }
}

Output: 4 8 12 16 20


When we work with arrays, we need to use the stream() method from the Arrays class to create a Stream of its elements.

Data structures that belong to the Collection Framework in Java inherit the method stream().

Example 2:
Write a program that takes a list of strings, counts all the elements whose length is greater than 5, and returns the final count.

class Test {

  public static void main(String[] args) {
    List<String> names = new ArrayList<>(Arrays.asList("Steve", "Melissa", "Megan", "Joshua", "Alexander", "Jim", "Paul"));

    long count = names.stream()
            .filter(str -> str.length() > 5) // intermediate operation
            .count();  // terminal operation
    System.out.println("Total count of names that have more than 5 characters: " + count);
  }
}

Output: Total count of names that have more than 5 characters: 3


We can use as many intermediate operations as we want, but only one terminal operation.

That’s it! Happy coding!

 

Leave a Reply

Your email address will not be published.