close
The Wayback Machine - https://web.archive.org/web/20240524192103/https://www.geeksforgeeks.org/stream-in-java/
Open In App

Stream In Java

Last Updated : 08 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Introduced in Java 8, Stream API is used to process collections of objects. A stream in Java is a sequence of objects that supports various methods which can be pipelined to produce the desired result. 

Use of Stream in Java

There uses of Stream in Java are mentioned below:

  1. Stream API is a way to express and process collections of objects.
  2. Enable us to perform operations like filtering, mapping,reducing and sorting.

How to Create Java Stream?

Java Stream Creation is one of the most basic steps before considering the functionalities of the Java Stream. Below is the syntax given on how to declare Java Stream.

Syntax

Stream<T> stream;

Here T is either a class, object, or data type depending upon the declaration.

Java Stream Features

The features of Java stream are mentioned below:

  • A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
  • Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
  • Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.

Different Operations On Streams

There are two types of Operations in Streams:

  1. Intermediate Operations
  2. Terminate Operations

Intermediate Operations

java stream operations

Intermediate Operations are the types of operations in which multiple methods are chained in a row.

Characteristics of Intermediate Operations

  1. Methods are chained together.
  2. Intermediate operations transform a stream into another stream.
  3. It enables the concept of filtering where one method filters data and passes it to another method after processing.

Benefit of Java Stream

There are some benefits because of which we use Stream in Java as mentioned below:

  • No Storage
  • Pipeline of Functions
  • Laziness
  • Can be infinite
  • Can be parallelized
  • Can be created from collections, arrays, Files Lines, Methods in Stream, IntStream etc.

Important Intermediate Operations

There are a few Intermediate Operations mentioned below:

1. map()

The map method is used to return a stream consisting of the results of applying the given function to the elements of this stream.

List number = Arrays.asList(2,3,4,5);
List square = number.stream().map(x->x*x).collect(Collectors.toList());

2. filter()

The filter method is used to select elements as per the Predicate passed as an argument.

List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().filter(s->s.startsWith("S")).collect(Collectors.toList());

3. sorted()

The sorted method is used to sort the stream.

List names = Arrays.asList("Reflection","Collection","Stream");
List result = names.stream().sorted().collect(Collectors.toList());

Terminal Operations

Terminal Operations are the type of Operations that return the result. These Operations are not processed further just return a final result value.

Important Terminal Operations

There are a few Terminal Operations mentioned below:

1. collect()

The collect method is used to return the result of the intermediate operations performed on the stream.

List number = Arrays.asList(2,3,4,5,3);
Set square = number.stream().map(x->x*x).collect(Collectors.toSet());

2. forEach()

The forEach method is used to iterate through every element of the stream.

List number = Arrays.asList(2,3,4,5);
number.stream().map(x->x*x).forEach(y->System.out.println(y));

3. reduce()

The reduce method is used to reduce the elements of a stream to a single value. The reduce method takes a BinaryOperator as a parameter.

List number = Arrays.asList(2,3,4,5);
int even = number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i);

Here ans variable is assigned 0 as the initial value and i is added to it.

Note: Intermediate Operations are running based on the concept of Lazy Evaluation, which ensures that every method returns a fixed value(Terminal operation) before moving to the next method.

Example of Java Stream

Java




// Java program to demonstrate
// the use of stream in java
import java.util.*;
import java.util.stream.*;
 
class Demo {
    public static void main(String args[])
    {
        // create a list of integers
        List<Integer> number = Arrays.asList(2, 3, 4, 5);
 
        // demonstration of map method
        List<Integer> square
          = number.stream()
            .map(x -> x * x)
            .collect(Collectors.toList());
 
        // create a list of String
        List<String> names = Arrays.asList(
            "Reflection", "Collection", "Stream");
 
        // demonstration of filter method
        List<String> result
          = names.stream()
            .filter(s -> s.startsWith("S"))
            .collect(Collectors.toList());
       
        System.out.println(result);
 
        // demonstration of sorted method
        List<String> show
          = names.stream()
            .sorted()
            .collect(Collectors.toList());
       
        System.out.println(show);
 
        // create a list of integers
        List<Integer> numbers
            = Arrays.asList(2, 3, 4, 5, 2);
 
        // collect method returns a set
        Set<Integer> squareSet
          = numbers.stream()
            .map(x -> x * x)
            .collect(Collectors.toSet());
       
        System.out.println(squareSet);
 
        // demonstration of forEach method
        number.stream()
            .map(x -> x * x)
            .forEach(y -> System.out.println(y));
 
        // demonstration of reduce method
        int even
          = number.stream()
            .filter(x -> x % 2 == 0)
            .reduce(0, (ans, i) -> ans + i);
 
        System.out.println(even);
    }
}


Output

[4, 9, 16, 25]
[Stream]
[Collection, Reflection, Stream]
[16, 4, 9, 25]
4
9
16
25
6

Important Points/Observations of Java Stream

  1. A stream consists of a source followed by zero or more intermediate methods combined together (pipelined) and a terminal method to process the objects obtained from the source as per the methods described.
  2. Stream is used to compute elements as per the pipelined methods without altering the original value of the object.


Previous Article
Next Article

Similar Reads

Difference between Stream.of() and Arrays.stream() method in Java
Arrays.stream() The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Example: Java Code // Java program to demonstrate Arrays.stream() method import java.uti
5 min read
Character Stream Vs Byte Stream in Java
A stream is a sequence of data. I/O Stream refers to a stream that is unlikely a method to sequentially access a file. I/O Stream means an input source or output destination representing different types of sources e.g. disk files. The java.io package provides classes that allow you to convert between Unicode character streams and byte streams of no
4 min read
Java Program to Convert String to Char Stream Without Using Stream
Char stream defines the array of characters. In this article, we will learn the different types of methods for converting a String into a char stream in Java without using Stream. Let us see some methods one by one. ExamplesInput: String = HelloGeeksOutput: [H, e, l, l, o, G, e, e, k, s] Input: String = Introduction Output: [I, n, t, r, o, d, u, c,
4 min read
foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
Java Stream | Collectors toCollection() in Java
Collectors toCollection(Supplier&lt;C&gt; collectionFactory) method in Java is used to create a Collection using Collector. It returns a Collector that accumulates the input elements into a new Collection, in the order in which they are passed. Syntax: public static &lt;T, C extends Collection&lt;T&gt;&gt; Collector&lt;T, ?, C&gt; toCollection(Supp
2 min read
stream.limit() method in Java
Prerequisite : Streams in Java8 The limit(long N) is a method of java.util.stream.Stream object. This method takes one (long N) as an argument and returns a stream of size no more than N. limit() can be quite expensive on ordered parallel pipelines, if the value of N is large, because limit(N) is constrained to return the first N elements in the en
2 min read
Stream skip() method in Java with examples
Prerequisite : Streams in java The skip(long N) is a method of java.util.stream.Stream object. This method takes one long (N) as an argument and returns a stream after removing first N elements. skip() can be quite expensive on ordered parallel pipelines, if the value of N is large, because skip(N) is constrained to skip the first N elements in the
3 min read
Stream.reduce() in Java with examples
Many times, we need to perform operations where a stream reduces to single resultant value, for example, maximum, minimum, sum, product, etc. Reducing is the repeated process of combining all elements. reduce operation applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previou
3 min read
Stream.concat() in Java
Stream.concat() method creates a concatenated stream in which the elements are all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel. Syntax : static &lt;T&gt; Stream&lt;T&gt; concat(Str
4 min read
Stream.distinct() in Java
distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable. But, in case of unordered streams, the selection of distinct elements is not neces
2 min read
Practice Tags :