Java Stream reuse – traverse stream multiple times?

Is it possible to reuse streams in Java? Learn the alternative of Java stream reuse.

1. Can we reuse stream? No.

Java streams, once consumed, can not be reused by default. As Java docs say clearly,

“A stream should be operated on (invoking an intermediate or terminal stream operation) only once. This rules out, for example, “forked” streams, where the same source feeds two or more pipelines, or multiple traversals of the same stream. A stream implementation may throw IllegalStateException if it detects that the stream is being reused.”

So the simple answer is : NO, we cannot reuse the streams or traverse the streams multiple times. Any attempt to do so will result in error : Stream has already been operated on or closed.

2. Solution

First of all, any implementation code which require to traverse the stream multiple times – isn’t efficient code and need to be refactored.

Only usecase where you might want to create a source and get stream multiple times is – unit testing. In that case, we can always use stream() method or just create a fresh stream.

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

public class Main 
{
	public static void main(String[] args) 
	{
		List<Integer> tokens = Arrays.asList(1, 2, 3, 4, 5);
		
		//first use
		Optional<Integer> result = tokens.stream().max(Integer::compareTo);
		System.out.println(result.get());
		
		//second use
		result = tokens.stream().min(Integer::compareTo);
		System.out.println(result.get());
		
		//third use
		long count = tokens.stream().count();
		System.out.println(count);
	}
}

Program output.

5
1
5

Reference :

Java Stream Interface

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.