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

Stream In Java

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 that can be pipelined to produce the desired result. 

Use of Stream in Java:

The 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 for declaring 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

  • Methods are chained together.
  • Intermediate operations transform a stream into another stream.
  • 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.

Syntax:

<R> Stream<R> map(Function<? super T, ? extends R> mapper)

2. filter()

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

Syntax:

Stream<T> filter(Predicate<? super T> predicate)

3. sorted()

The sorted method is used to sort the stream.

Syntax:

Stream<T> sorted()
Stream<T> sorted(Comparator<? super T> comparator)

4.flatMap()

Syntax:

The flatMap operation in Java Streams is used to flatten a stream of collections into a single stream of elements.

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)

5. distinct ()
Removes duplicate elements. It returns a stream consisting of the distinct elements (according to Object.equals(Object)).

Syntax:

Stream<T> distinct()

6. peek()

Performs an action on each element without modifying the stream. It returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.

Syntax:

Stream<T> peek(Consumer<? super T> action)


Java program that demonstrates the use of all the intermediate operations

Java
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class StreamIntermediateOperationsExample {
    public static void main(String[] args) {
        // List of lists of names
        List<List<String>> listOfLists = Arrays.asList(
            Arrays.asList("Reflection", "Collection", "Stream"),
            Arrays.asList("Structure", "State", "Flow"),
            Arrays.asList("Sorting", "Mapping", "Reduction", "Stream")
        );

        // Create a set to hold intermediate results
        Set<String> intermediateResults = new HashSet<>();

        // Stream pipeline demonstrating various intermediate operations
        List<String> result = listOfLists.stream()
            .flatMap(List::stream)               // Flatten the list of lists into a single stream
            .filter(s -> s.startsWith("S"))      // Filter elements starting with "S"
            .map(String::toUpperCase)            // Transform each element to uppercase
            .distinct()                          // Remove duplicate elements
            .sorted()                            // Sort elements
            .peek(s -> intermediateResults.add(s)) // Perform an action (add to set) on each element
            .collect(Collectors.toList());       // Collect the final result into a list

        // Print the intermediate results
        System.out.println("Intermediate Results:");
        intermediateResults.forEach(System.out::println);

        // Print the final result
        System.out.println("Final Result:");
        result.forEach(System.out::println);
    }
}

Output
Intermediate Results:
STRUCTURE
STREAM
STATE
SORTING
Final Result:
SORTING
STATE
STREAM
STRUCTURE

Explanation of the above Program:

List of Lists Creation:

  • The listOfLists is created as a list containing other lists of strings.

Stream Operations:

  • flatMap(List::stream): Flattens the nested lists into a single stream of strings.
  • filter(s -> s.startsWith("S")): Filters the strings to only include those that start with “S”.
  • map(String::toUpperCase): Converts each string in the stream to uppercase.
  • distinct(): Removes any duplicate strings.
  • sorted(): Sorts the resulting strings alphabetically.
  • peek(...): Adds each processed element to the intermediateResults set for intermediate inspection.
  • collect(Collectors.toList()): Collects the final processed strings into a list called result.

The program prints the intermediate results stored in the intermediateResults set. Finally, it prints the result list, which contains the fully processed strings after all stream operations.

This example showcases how Java Streams can be used to process and manipulate collections of data in a functional and declarative manner, applying transformations and filters in a sequence of operations.

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.

Syntax:

<R, A> R collect(Collector<? super T, A, R> collector)

2. forEach()

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

Syntax:

void forEach(Consumer<? super T> action)

3. reduce()

Syntax:

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.

T reduce(T identity, BinaryOperator<T> accumulator)
Optional<T> reduce(BinaryOperator<T> accumulator)

4. count()
Returns the count of elements in the stream.

Syntax:

long count()

5. findFirst()

Returns the first element of the stream, if present.

Syntax:

Optional<T> findFirst()

6. allMatch()
Checks if all elements of the stream match a given predicate.

Syntax:

boolean allMatch(Predicate<? super T> predicate)

7. anyMatch()

Checks if any element of the stream matches a given predicate.

Syntax:

boolean anyMatch(Predicate<? super T> predicate)

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.

Java Program Using All Terminal Operations

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

public class StreamTerminalOperationsExample {
    public static void main(String[] args) {
        // Sample data
        List<String> names = Arrays.asList(
            "Reflection", "Collection", "Stream",
            "Structure", "Sorting", "State"
        );

        // forEach: Print each name
        System.out.println("forEach:");
        names.stream().forEach(System.out::println);

        // collect: Collect names starting with 'S' into a list
        List<String> sNames = names.stream()
                                   .filter(name -> name.startsWith("S"))
                                   .collect(Collectors.toList());
        System.out.println("\ncollect (names starting with 'S'):");
        sNames.forEach(System.out::println);

        // reduce: Concatenate all names into a single string
        String concatenatedNames = names.stream().reduce(
            "",
            (partialString, element) -> partialString + " " + element
        );
        System.out.println("\nreduce (concatenated names):");
        System.out.println(concatenatedNames.trim());

        // count: Count the number of names
        long count = names.stream().count();
        System.out.println("\ncount:");
        System.out.println(count);

        // findFirst: Find the first name
        Optional<String> firstName = names.stream().findFirst();
        System.out.println("\nfindFirst:");
        firstName.ifPresent(System.out::println);

        // allMatch: Check if all names start with 'S'
        boolean allStartWithS = names.stream().allMatch(
            name -> name.startsWith("S")
        );
        System.out.println("\nallMatch (all start with 'S'):");
        System.out.println(allStartWithS);

        // anyMatch: Check if any name starts with 'S'
        boolean anyStartWithS = names.stream().anyMatch(
            name -> name.startsWith("S")
        );
        System.out.println("\nanyMatch (any start with 'S'):");
        System.out.println(anyStartWithS);
    }
}

Output
forEach:
Reflection
Collection
Stream
Structure
Sorting
State

collect (names starting with 'S'):
Stream
Structure
Sorting
State

reduce (concatenated names):
Reflection Collection Stream Structure So...

Explanation of the above Program:

List Creation:

  • The names list is created with sample strings.

Stream Operations:

  • forEach: Prints each name in the list.
  • collect: Filters names starting with ‘S’ and collects them into a new list.
  • reduce: Concatenates all names into a single string.
  • count: Counts the total number of names.
  • findFirst: Finds and prints the first name in the list.
  • allMatch: Checks if all names start with ‘S’.
  • anyMatch: Checks if any name starts with ‘S’.

The program prints each name, names starting with ‘S’, concatenated names, the count of names, the first name, whether all names start with ‘S’, and whether any name starts with ‘S’.

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
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 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.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
Stream sorted() in Java
Stream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when processing new elements. Syntax
2 min read
Stream.max() method in Java with Examples
Stream.max() returns the maximum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. max() is a terminal operation which combines stream elements and returns a summary result. So, max() is a special case of reduction. The method returns Optional
3 min read
Stream sorted (Comparator comparator) method in Java
Stream sorted(Comparator comparator) returns a stream consisting of the elements of this stream, sorted according to the provided Comparator. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may incorporate state from previously seen elements when p
3 min read
Stream min() method in Java with Examples
Stream.min() returns the minimum element of the stream based on the provided Comparator. A Comparator is a comparison function, which imposes a total ordering on some collection of objects. min() is a terminal operation which combines stream elements and returns a summary result. So, min() is a special case of reduction. The method returns Optional
2 min read
Stream generate() method in Java with examples
Stream generate(Supplier&lt;T&gt; s) returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc. Syntax : static &lt;T&gt; Stream&lt;T&gt; generate(Supplier&lt;T&gt; s) Where, Stream is an interface and T is the type of s
1 min read
Stream count() method in Java with examples
long count() returns the count of elements in the stream. This is a special case of a reduction (A reduction operation takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation). This is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
2 min read
Stream.of(T... values) in Java with examples
Stream of(T... values) returns a sequential ordered stream whose elements are the specified values. A sequential stream work just like for-loop using a single core. On the other hand, a Parallel stream divide the provided task into many and run them in different threads, utilizing multiple cores of the computer. Syntax : static &lt;T&gt; Stream&lt;
2 min read
Stream.of(T t) in Java with examples
Stream of(T t) returns a sequential Stream containing a single element i.e, a singleton sequential stream. A sequential stream work just like for-loop using a single core. On the other hand, a Parallel stream divide the provided task into many and run them in different threads, utilizing multiple cores of the computer. Syntax : static &lt;T&gt; Str
2 min read
Stream map() in Java with examples
Stream map(Function mapper) returns a stream consisting of the results of applying the given function to the elements of this stream. Stream map(Function mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance
3 min read
Stream mapToInt() in Java with examples
Stream mapToInt(ToIntFunction mapper) returns an IntStream consisting of the results of applying the given function to the elements of this stream. Stream mapToInt(ToIntFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, the
2 min read
Stream mapToLong() in Java with examples
Stream mapToLong(ToLongFunction mapper) returns a LongStream consisting of the results of applying the given function to the elements of this stream. Stream mapToLong(ToLongFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing,
2 min read
Stream mapToDouble() in Java with examples
Stream mapToDouble (ToDoubleFunction mapper) returns a DoubleStream consisting of the results of applying the given function to the elements of this stream. Stream mapToDouble (ToDoubleFunction mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their
2 min read
Stream allMatch() in Java with examples
Stream allMatch(Predicate predicate) returns whether all elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result. This is a short-circuiting terminal operation. A terminal operation is short-circuiting if, when presented with infinite input, it may terminate
3 min read
Stream anyMatch() in Java with examples
Stream anyMatch(Predicate predicate) returns whether any elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result. This is a short-circuiting terminal operation. A terminal operation is short-circuiting if, when presented with infinite input, it may terminate
2 min read
Stream findFirst() in Java with examples
Stream findFirst() returns an Optional (a container object which may or may not contain a non-null value) describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned. Syntax : Optional&lt;T&gt; findFirst() Where, Optional is a container object which
2 min read
Stream flatMapToDouble() in Java with examples
Stream flatMapToDouble(Function mapper) returns an DoubleStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Stream flatMapToDouble(Function mapper) is an intermediate operation. These operations are always lazy. Intermedia
2 min read
Stream flatMapToLong() in Java with examples
Stream flatMapToLong(Function mapper) applies given mapper function to each element of a stream and returns a LongStream. Stream flatMapToLong(Function mapper) is an intermediate operation. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output. Note : Each mapped strea
3 min read
Stream flatMapToInt() in Java with examples
Stream flatMapToInt(Function mapper) returns an IntStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Stream flatMapToInt(Function mapper) is an intermediate operation. These operations are always lazy. Intermediate operat
2 min read
Stream forEach() method in Java with examples
Stream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEach(Consumer&lt;? super T&gt; action) Where, Consumer is a functional interface and T is the type of stream elements. Note
2 min read
Stream forEachOrdered() method in Java with examples
Stream forEachOrdered(Consumer action) performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. Stream forEachOrdered(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEachOrdered(Consumer&lt;? s
2 min read
Stream noneMatch() Method in Java with Examples
A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. noneMatch() of Stream class returns whether no elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result. This is a short-circuiting terminal
3 min read
Sum of list with stream filter in Java
We generally iterate through the list when adding integers in a range, but java.util.stream.Stream has a sum() method that when used with filter() gives the required result easily. Java Code // Simple method (without filter) to find sum of a list import java.util.*; class Addition { public static void main(String[] args) { // create a list of integ
2 min read
Convert Stream to Set in Java
Below given are some methods which can be used to convert Stream to Set in Java. Method 1 : Using Collectors Stream collect() method takes elements from a stream and stores them in a collection.collect(Collector.toSet()) collects elements from a stream to a Set. Stream.collect() method can be used to collect elements of a stream in a container. The
3 min read
Practice Tags :