Stream API in java8

  • By
  • November 3, 2022
  • JAVA
Java 8 Stream A Stream in Java can be defined as a sequence of elements which are taken from a source collection. The source of elements can be a Collection or Array that provides data to the Stream. Java 8 consists of a new additional package called java.util.stream. This package consists of classes, interfaces and methods to allow functional-style operations on the elements. We need to import java.util.stream package to use Stream API in the programming Java streams are designed in such a way that most of the stream operations return a Stream as a result and such operations are called intermediate operations. This helps to create a chain of stream operations. This is called stream pipe-lining. Stream vs Collection? A Collection is an in-memory data structure, which consists of all the values that the data structure currently has. Every element in the Collection has to be evaluated before it can be added to the stream. While a Stream is conceptually a pipeline,in which it does not consist of all the elements of Collection rather than it consists of some of the elements from collection. We can say that Collection is the whole data structure whereas Stream is some of the part of that data structure. The idea is that a user will extract only the values they require from a Stream as and when required and this stream is generated from Collection. For example, if we have 500 elements from 0-500 and we want only the even elements from that 500 elements. So, here in this case the all 500 elements are nothing but collection whereas the even numbers(some of the part of whole collection) which we requires is nothing but stream Why use the Stream API? -Compared to the pre-Java 8 code, the code which is written using Stream API is far more concise. -The stream API allows you to perform operations on collections without external iteration means here we don't have to write any code or iterations to get stream from Collections. We just have to use some of the inbuilt methods like stream(),filter(), map() from Stream API -In this case, we’re performing a filter operation which will filter the input collection based on the condition specified and after applying that condition we will get a stream. -Streams provide the most convenient and natural way to apply various kinds of functions to the sequences of objects. How does Streams work? The Stream API performs all the operations in the format lambda expressions(one line arrow function) can be used to perform bulk operations on Collections without the need for external iteration. The basic interface in the Stream API is called the 'java.util.Stream', and there are various methods available in the Stream interface that perform various operations on the Stream object. In the above example of getting even numbers from 1-500 we're calling the filter method. The filter method accepts a Predicate or condition instance which is an in-built functional interface. This lambda expression accepts an integer value from 1-500 one by one, checks if it is divisible by 2 or not and returns a Boolean value accordingly. The filter operation executes this lambda expression on every element in the input Stream and it creates a new Stream with the output. The result? A Stream with only values of even numbers from 1-500. An important point to remember is that Streams does not modify the underlying collection and the data in that underlying collection will not be affected by the Stream operations. Java 8 Stream has many operations which can be pipelined together to get the desired result. All the operations on streams can be performed by using methods. Some methods produce or return another stream as a result and some methods produce or return non-stream values as a result. The operations which return another stream as a result are called intermediate operations and the operations which return non-stream values like primitive or object or collection or return nothing are called terminal operations. As the names suggest, intermediate operations don't give end results. It just transforms one stream to another stream. On the other hand, terminal operations give end results directly. Methods of Java Stream API Filter: It filters elements based upon a condition or predicate we provide to that filter method. For example, if your list contains numbers and you want only the numbers which are divisible by 5 then you can use the filter method to only select a number divisible by 5. The filter method essentially selects elements based upon a condition you provided to it. That’s the reason that the filter (Predicate condition) accepts a Predicate object, which provides a function that is applied to a condition. The filter operation cannot be applied on all the elements of a stream Map : The map() function needs to be applied on all the elements of a stream In simple words, the map() is used to transform one object into another object by applying a function on that objects. It is also an intermediate Stream operation which means after calling map() it generates another stream and we need to call another Stream method, like a filter, or collect on this to create a chain of streams. That’s the reason the Stream.map(Function mapper) takes a function or lambda expression as an argument. For an example, by applying the map() function on stream, you can convert a list of String into a List of Integer by applying the Integer.valueOf() method to each String on the input list. If the condition is computed as a true, then the object is selected. Otherwise, it will be ignored. collect: The collect() method is used to collect the result in a list, set, map or any other collection. collect() method is called as the terminal methods because here, the operation gets terminated with some outcome. Functions associated with Collectors usually get used inside collect() methods. Collectors class is part of Stream package and can be imported as: import static java.util.stream.Collectors.*; Class Hierarchy: java.lang.Object java.util.stream class Collectors What is collect in stream in Java? java Stream collect() is mostly used to collect the stream elements to a collection. OR The Stream.collect() method used to receive elements from a stream and store them in a collection. Collectors.toList() The toList() collector method can be used for collecting all Stream elements into a List object. Collectors.toSet() The toSet collector method can be used for collecting all Stream elements into a Set object. Collectors.toMap() The toMap collector method can be used to collect Stream elements into a Map object. To do this, we need to provide two functions: keyMapper valueMapper We'll use keyMapper to extract a Map key from a Stream element, and valueMapper to extract a value associated with a given key. Collectors.counting() Counting is a simple collector method that allows for the counting of all elements of a stream.

Stream API in java8

Java 8 Stream

 

A Stream in Java can be defined as a sequence of elements which are  taken from a source collection. The source of elements can be a Collection or Array that provides data to the Stream.

 

Java 8 consists of a new additional package  called java.util.stream. This package consists of classes, interfaces and methods  to allow functional-style operations on the elements.

 

We need to import java.util.stream package to use Stream API in the programming

 

Java streams are designed in such a way that most of the stream operations return a Stream as a result and such operations are called intermediate operations. This helps to create a chain of stream operations. This is called stream pipe-lining.

 

For Free, Demo classes Call: 020-71173125
Registration Link: Click Here!

 

Stream vs Collection?

 

A Collection is an in-memory data structure, which consists of all the values that the data structure currently has. 

 

Every element in the Collection has to be evaluated before it can be added to the stream. 

 

While a Stream is conceptually a pipeline,in which it does not consist of all the elements of Collection rather than it consists of some of the elements from collection. We can say that Collection is the whole data structure whereas  Stream is some of the part of that data structure.

 

The idea is that a user will extract only the values they require from a Stream as and when required and this stream is generated from Collection.

 

For example, if we have 500 elements from 0-500 and we want only the even elements from that 500 elements. So, here in this case the all 500 elements are nothing but collection whereas the even numbers(some of the part of whole collection) which we requires is nothing but stream.

 

For Free, Demo classes Call: 020-71173125
Registration Link: Click Here!

 

Why use the Stream API?

 

-Compared to the pre-Java 8 code, the code which is written using Stream API is far more concise.

 

-The stream API allows you to perform operations on collections without external iteration means here we don’t have to write any code or iterations to get stream from Collections. We just have to use some of the inbuilt methods like stream(),filter(), map() from Stream API

 

-In this case, we’re performing a filter operation  which will filter the input collection based on the condition specified and after applying that condition we will get a stream.

 

-Streams provide the most convenient and natural way to apply various kinds of functions to the sequences of objects.

 

How does Streams work?

 

The Stream API performs all the operations in the format lambda expressions(one line arrow function) can be used to perform bulk operations on Collections without the need for external iteration. The core idea behind the static factory method is to create and return instances wherein the details of the class module are hidden from the user at where we have created those instances for the Java classes in Pune.

 

The basic interface in the Stream API is called the ‘java.util.Stream’, and there are various methods available in the  Stream interface that perform various operations on the Stream object.

 

In the above example of getting even numbers from 1-500 we’re calling the filter method. The filter method accepts a Predicate or condition instance which is an in-built functional interface. 

 

This lambda expression accepts an integer value from 1-500 one by one, checks if it is divisible by 2 or not and returns a Boolean value accordingly. 

 

The filter operation executes this lambda expression on every element in the input Stream and it creates a new Stream with the output. The result? A Stream with only values of even numbers from 1-500.

 

An important point to remember is that Streams does not modify the underlying collection and the data in that underlying collection will not be affected by the Stream operations.

 

Java 8 Stream has many operations which can be pipelined together to get the desired result. All the operations on streams can be performed by using methods. Some methods produce or return another stream as a result and some methods produce or return non-stream values as a result. The operations which return another stream as a result are called intermediate operations and the operations which return non-stream values like primitive or object or collection or return nothing are called terminal operations. 

 

As the names suggest, intermediate operations don’t give end results. It  just transforms one stream to another stream. On the other hand, terminal operations give end results directly.

 

Methods of Java Stream API

 

Filter:

 

It filters elements based upon a condition or predicate we provide to that filter method. For example, if your list contains numbers and you want only the numbers which are divisible by 5 then you can use the filter method to only select a number divisible by 5.

 

The filter method essentially selects elements based upon a condition you provided to it. That’s the reason that the filter (Predicate condition) accepts a Predicate object, which provides a function that is applied to a condition. The filter operation cannot be applied on all the elements of a stream

 

Map :

 

The map() function needs to be applied on all the elements of a stream

 

In simple words, the map() is used to transform one object into another object by applying a function on that objects.

 

It is also an intermediate Stream operation which means after calling map() it generates another stream and we need to call another Stream method, like a filter, or collect on this to create a chain of streams.

 

That’s the reason the Stream.map(Function mapper) takes a function or lambda expression as an argument. 

 

For an  example, by applying  the map() function on stream, you can convert a list of String into a List of Integer by applying the Integer.valueOf() method to each String on the input list.

 

If the condition is computed as a  true, then the object is selected. Otherwise, it will be ignored.

 

collect:

 

The collect() method is used to collect the result in a list, set, map or any other collection.

 

collect()  method is called as the terminal methods because here, the operation gets terminated with some outcome. Functions associated with Collectors usually get used inside collect() methods. Collectors class is part of Stream package and can be imported as:

 

import static java.util.stream.Collectors.*;

Class Hierarchy:

 

java.lang.Object

       java.util.stream

            class Collectors

 

What is collect in stream in Java?

 

java Stream collect() is mostly used to collect the stream elements to a collection.

 

OR

 

The Stream.collect() method used to receive elements from a stream and store them in a collection.

 

For Free, Demo classes Call: 020-71173125
Registration Link: Click Here!

 

Collectors.toList()

The toList() collector method  can be used for collecting all Stream elements into a List object. 

 

Collectors.toSet()

The toSet collector method can be used for collecting all Stream elements into a Set object. 

 

Collectors.toMap()

The toMap collector method can be used to collect Stream elements into a Map object. To do this, we need to provide two functions:

 

keyMapper

valueMapper

We’ll use keyMapper to extract a Map key from a Stream element, and valueMapper to extract a value associated with a given key.

 

Collectors.counting()

Counting is a simple collector method that allows for the counting of all elements of a stream.

 

Author:-

Pooja Nandode-Bhavsar

Call the Trainer and Book your free demo class for now!!!

© Copyright 2020 | Sevenmentor Pvt Ltd.

Submit Comment

Your email address will not be published.

*
*