Advance Interview Questions on Streams API

Vikas Taank
3 min readDec 28, 2023

--

Explain the Difference Between Intermediate and Terminal Operations for Streams API.

Intermediate Operations:

  • Intermediate Operations are characterized by their Lazy Execution; that means they don’t perform any processing until a terminal operation is invoked.
  • Return type of the intermediate operations are Streams so that they can be chained further.
  • Most Intermediate operations are stateless. They process elements independently, such as filter or map.
  • Some of the intermediate operations could be stateful, that means they need to process the entire input stream to produce a result. For example sorted and Distinct.

Intermediate Operations Examples:

  • map: Transforms each element of the stream.
  • filter: Filters elements based on a condition.
  • sorted: Sorts the stream.
  • limit: Limits the number of elements.
  • distinct: Removes duplicate elements.

Terminal Operations

  • Terminal operation trigger the processing of data and produce results.
  • Return Type could be aggregate , collection or could be Optional.
  • Terminal operations process the stream immediately as they are non-lazy.
  • You can’t chain the stream after terminal operation.

Common Examples:

  • forEach: Performs an action for each element of the stream.
  • collect: Gathers elements into a collection or another form of aggregate data structure.
  • reduce: Combines elements to produce a single summary result.
  • anyMatch, allMatch, noneMatch: Check if some or all elements match a given condition.
  • findFirst, findAny: Return an element from the stream.
List<String> modifiedList = list.stream()   // stream() is neither, just a stream source
.filter(s -> s.startsWith("A")) // Intermediate
.map(String::toUpperCase) // Intermediate
.collect(Collectors.toList()); // Terminal

Explain the purpose and usage of primitive streams

IntStream, DoubleStream, LongStream have been provided in order to:

  1. Improve performance overhead of boxing and Unboxing.
  2. To provide specialized methods like sum, avg, max, min.
  3. Less memory foot print by using primitive.

Creating primitive Streams.

int[] numbers = {1, 2, 3, 4, 5};
IntStream numberStream = Arrays.stream(numbers);

Using Factory Methods.

IntStream rangeStream = IntStream.range(1, 6); // 1, 2, 3, 4, 5

Aggregation

int sum = IntStream.of(1, 2, 3, 4, 5).sum();

Mapping

IntStream.of(1, 2, 3).map(n -> n * n); 
// Square of each number

Filtering

OptionalInt firstEven = IntStream.of(1, 2, 3, 4).filter(n -> n % 2 == 0).findFirst();
//Terminal Operation

What is the difference between forEach and forEachOrdered in a stream

forEach

does not preserve the order in parallel stream processing. As this does not preserve order it is more efficient and used in the cases where ordering is not important.

forEachOrdered

preserve the order in parallel processing and also less efficient as different thread needs to communicate about the order state in the scenarios of parallel processing.

Sequential Stream

In Sequential stream there is not difference between forEach and forEachOrdered as the stream is already Sequential.

Parallel Stream

In a parallel stream use case forEach can process elements simultaneously in any order, leading to non-deterministic behavior, whereas forEachordered respects the order defined by the stream's source or its operations.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

// Using forEach in a parallel stream
numbers.parallelStream().forEach(n -> System.out.println(n));

// Using forEachOrdered in a parallel stream
numbers.parallelStream().forEachOrdered(n -> System.out.println(n));

For first scenario the order of the element may change every time you run the program however in second scenario , the order will be same every time you run the program.

Why would you use forEachOrdered

There could be many scenarios like:

  1. Processing records from a file where we need to maintain the order of the records in the file.
  2. Preserving the order while using the parallel streams.
  3. Collection elements in order.
  4. Maintaining Logical Sequence in order.

Most of the above questions have been asked to me in many interviews and I wanted to summarize these and I hope you would like this content. Please share and clap.

--

--

Vikas Taank

I am new to Medium, trying to articulate my learnings so far . Please Join medium to read my articles. Please support- https://ko-fi.com/vikastaank