Top 10 Stream API Interview Questions and Answers

In this post, I will be sharing top 10 Stream API interview questions and answers for experienced Java professionals. I have already shared the frequently asked Java 8 programming interview questions. Please bookmark this page, I will keep adding more Stream related interview questions to this post.

Read Also: Java 8 Interview Questions and Answers

Stream Interview Questions and Answers

Q1 Why Stream API is used?

Streams tend to not modify the underlying collection. In a stream pipeline every element is visited only once.

Functional programming, Stream provides the most natural & convenient way to apply functions to sequences of objects.

Q2 What is intermediate operation?

Intermediate operation process the current stream data (if any) and then return a new stream.

When an intermediate operation is executed, it actually does not do anything but actually creates a new stream.

When we will traverse this newly created stream, we will see that this stream contains data of the initial stream that satisfies the predicate defined by the stream.

Examples:

map()
limit()
filter()
skip()
flatMap()
sorted()
distinct()
peek()

Q3 What is terminal operation?

Terminal operations as the name suggests are the last in pipeline of operations performed on a stream.

Terminal operation traverses the stream and either produces a result or a collection but not a new stream.

A stream pipeline consists of a source (such as a Collection, an array, a generator function, or an I/O channel), it will invoke all the intermediate operations in the pipeline and lastly the terminal operation is performed which marks the stream pipeline considered consumed and is marked closed.

We can have only one terminal operation at the end of the pipeline. If any operation performed on closed stream, it will result in a java.lang.IllegalStateException: stream has already been operated upon or closed.

Examples

collect()
forEach()
forEachOrdered()
findAny()
findFirst()
toArray()
reduce()
count()
min()
max()
anyMatch()
allMatch()
noneMatch()

Q4 What is stateful and stateless intermediate operations?

Stateful operations are skip(), distinct(),limit() and sorted(). Rest all other stream operations are stateless.

When an operation requires to retain the information of the elements/values it has processed so far in order to process the current element/value then it is a stateful operation.

For ex: Distinct operation requires to keep track of all the values it has processed so far, based on this information only it can decide that whether the current value is a unique value or it have been processed before and accordingly either will add the current value to the new stream(which is the output of the distinct operation) or neglect the value and not add it to the new stream.

Q5 How exceptions can be handled, in Stream API operations?

Below we have described a way to make sure the stream pipeline execution finishes and making sure all exceptions traces are kept.

 import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Test {

	private String value;  //member variable

        // Argument Constructor to initialize member variable value
        // with the value passed as argument while
        // object of the class is created
	public Test(String value) {
		super();
		this.value = value;
	}
        //Getter Setter
	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}
        //Member method
	public static String doSomething(Test object) throws IOException {
		try {
			return object.getValue().toString();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void main(String[] args) {
		List<Test> myList = new ArrayList<>(); //List of type Test class
		myList.add(new Test("test1"));
		myList.add(new Test("test2"));
		myList.add(new Test(null));

		List<Throwable> exceptions = new ArrayList<>(); // List of type Throwable class
        //creating stream from myList		
        myList.stream().map(item -> {
		        	        try {
		        	                return doSomething(item); // executing this line for each element in myList
			                } catch (IOException e) {
		                	        exceptions.add(e); // adding exceptions as they occur to the list exceptions
				                return ""; // returning blank String in case of exception
			                }
		                    }).filter(s -> s.length() > 0).collect(Collectors.toList()); // collecting results in the list
	}
} 

Output:

Exception in thread "main" java.lang.RuntimeException: java.lang.NullPointerException: Cannot invoke "String.toString()" because the return value of "Test.getValue()" is null
   at Test.doSomething(Test.java:30)


Here we are keeping all the exception traces in a list that we can iterate to perform any further processing if needed or simply log them.

Q6 How Stream API is used to handle infinite data?

First, we create a stream object based on this infinite data
For example

Stream stream = Stream.iterate(0, value -> value + 1);

Here we are using iterate method of stream API to create a stream object of infinite data.
Value starts with zero and then keeps incrementing by one. Iterate is an intermediate operation.
Before applying a terminal operation we will have to limit data else the processing will never end as its infinite data.

Limit function is applied to limit the data.

Stream.iterate(0, value -> value + 1).limit(15).collect(Collectors.toSet());

So here, we are creating a set of first 15 values out from the infinite data.
Skip method can also be used here

Stream.iterate(0, value -> value + 1).skip(5).limit(15).collect(Collectors.toSet());

Here we skipped first five values and collected the next 15 values.

Q7 What does short-circuit behavior of Streams mean?

Short-circuit is an optimization technique supported by Stream API. It means that when we are processing input data, we arrive at a result, even before evaluating all the input data.
It supports many short-circuiting operations like findFirst, allMatch, anyMatch, limit, findAny.

For example, when we use the findFirst operation of the Stream API, it returns the first element of the stream and will not process the rest of the elements of the stream.

The Stream API supports short-circuiting of both intermediate and terminal operations.

The only intermediate short-circuiting method currently defined in the Stream API is limit.

Q8 How Stream API supports parallelism?

Stream API uses fork and join default pool to achieve parallelism. Number of threads in the default pool is equivalent to the number of processor cores.
Usage:

Optional<integer> result = list.parallelStream().reduce((x,y) -> x*y));

Reduce operation repeatedly applies a binary operation to every element in the stream. It takes two arguments, first argument is either the first element in the stream or the result of the previous reduce operation and second argument is the current element of the stream.

Reducing is the repeated process of combining all elements. Reduce operation applies a binary operation to each element in the stream where the first argument to the operation is the return value of the previous application and second argument is the current stream element.

Q9 What are the performance implications of using parallel streams?

When using parallel stream we need to consider few things like sometimes managing the splitting of source data between multiple threads and then merging the results becomes a very expensive task in comparison to the actual work itself and then also we may have to deal with issues related to memory locality .

Q10 In case of an array what should be used Loop or Stream?

When we use for loop to iterate over an array it’s very lightweight in terms of CPU usage and heap memory. If we want to consider only thriftiness of memory and raw speed then we should not use stream to iterate over an array.

That's all for today. Please mention in the comments if you have faced a different Stream API based question in the interview. 

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry