Java 8 Streams Operations

Java 8 Streams Operations thumbnail
9K
By Dhiraj 12 May, 2017

This tutorial is on java 8 streams API. Here we will be discussing about what is stream, different ways to obtain a stream and also about different stream operations with examples.

What is Stream

Stream can be defined as a sequence of elements or objects from any java collection supporting sequential and parallel aggregate operations. Java 8 streams does not require any storage. It simply streams any collection of elements, process the elements in parallel and again collects those resulting elements and returns a collection out of it.

How Streams Differ from Collection

Streams differ from collections in several ways:

A stream is not a data structure that stores elements; instead, it conveys elements from a source

An operation on a stream produces a result, but does not modify its source.

Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily.

The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.

Ways of Obtaining a stream

Streams can be obtained in a number of ways.

From a Collection via the stream() and parallelStream() methods. Following is an example

	List list = new ArrayList();
        
        Stream stream = list.stream();
        
        stream.forEach(System.out::println);
    

From an array via Arrays.stream(Object[]). Following is an example:

	String array[] = {"Ram", "Shyam", "Hari"};
        
        //stream from an array using Stream.of()
        Stream stream = Arrays.stream(array);
        
        stream.forEach(System.out::println);
Other Interesting Posts
Java 8 Lambda Expression
Java 8 Datetime Conversions
Java 8 Parallel Streams
Java 9 Modularity Features

Different Stream Operations

Stream operations are divided into intermediate and terminal operations.A stream pipeline may have zero or more intermediate operations such as Stream.filter or Stream.map but only one terminal operation such as Stream.forEach or Stream.reduce

Intermediate operations return a new stream. They are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Traversal of the pipeline source does not begin until the terminal operation of the pipeline is executed.

filter() - It is an intermediate operator and hence it requires a terminal operator like collect() or count() to process it.Below is an example that filters numbers more than 100.

package com.devglan;

import java.util.Arrays;
import java.util.List;

public class FunctionalInterfaceExample {

    public static void main(String[] args) {
       
        List numbers = Arrays.asList(120, 100, 80, 50, 400, 500);
        
        long count = numbers.stream().filter(number -> (number > 100)).count();
        System.out.println("number counts exceeding 100 " + count);
    }
    
}

map() - This method is used to map elements of a stream to another. Following is an example which will print the small alphabets to upper case as output.

package com.devglan;

import java.util.Arrays;
import java.util.List;

public class FunctionalInterfaceExample {

    public static void main(String[] args) {
       
    	 List input = Arrays.asList("a", "b", "c", "d", "e", "f", "g");
         
         input.stream().map(alpha -> alpha.toUpperCase())
                             .forEach(System.out::println);
    }
    
}

sorted() - It is an intermediate operator that sorts the elements in ascending order.

package com.devglan;

import java.util.Arrays;
import java.util.List;

public class FunctionalInterfaceExample {

    public static void main(String[] args) {
    	
         List input = Arrays.asList("f", "a", "z", "h", "j", "k", "g");
         
         input.stream().map(alpha -> alpha.toUpperCase())
                             .forEach(System.out::println);
    }
    
}

reduce()

It performs reduction operation that takes a sequence of input elements and combines them into a single summary result such as finding the sum or maximum of a set of numbers, or accumulating elements into a list.

package com.devglan;

import java.util.Arrays;
import java.util.List;

public class FunctionalInterfaceExample {

    public static void main(String[] args) {
    	
	List numbers = Arrays.asList(120, 100, 80, 50, 400, 500);
         
         int sum = numbers.stream().reduce(0, Integer::sum);
         System.out.println("Sum of numbers " + sum);
    }
    
}

output - 1250

Conclusion

I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.

Share

If You Appreciate This, You Can Consider:

We are thankful for your never ending support.

About The Author

author-image
A technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. Technical expertise in highly scalable distributed systems, self-healing systems, and service-oriented architecture. Technical Skills: Java/J2EE, Spring, Hibernate, Reactive Programming, Microservices, Hystrix, Rest APIs, Java 8, Kafka, Kibana, Elasticsearch, etc.

Further Reading on Java 8