0% found this document useful (0 votes)
11 views10 pages

Java Stream API Interview Guide

Uploaded by

Jigyarth Joshi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views10 pages

Java Stream API Interview Guide

Uploaded by

Jigyarth Joshi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Stream API – Complete Interview Guide & Coding Sheet

1. What is Stream API?

Stream API (Java 8) provides a functional, declarative way to process collections and arrays using
pipelines.
It supports filter-map-reduce, parallel processing, lazy evaluation, and eliminates boilerplate loops.

2. Why Use Streams?

• Cleaner, readable, and maintainable code

• Lazy execution improves performance

• Easy parallelism (parallelStream())

• Safe functional operations (no modification of source data)

3. Stream Pipeline (Very Important)

Source → Intermediate Ops (Lazy) → Terminal Ops (Eager)


Example:

[Link]().filter(x -> x>10).map(x -> x*x).collect([Link]());

4. Intermediate Operations (Lazy)

Operation Purpose

filter() Keep matching values

map() Transform values

flatMap() Flatten nested structures

distinct() Remove duplicates

sorted() Sort elements

limit()/skip() Pagination

peek() Debug pipeline

5. Terminal Operations (Eager)

Operation Purpose

collect() Convert stream to collection


Operation Purpose

forEach() Iterate values

reduce() Aggregate (sum/min/max)

count() Count elements

findFirst() First element

findAny() Fastest (parallel)

anyMatch()/allMatch()/noneMatch() Condition checks

6. map() vs flatMap()

• map() → transforms each element

• flatMap() → transforms + flattens (useful for List<List<T>> → List<T>)

7. Lazy Evaluation

Intermediate ops are stored but not executed until a terminal op runs.

8. Parallel Streams

• Uses [Link]()

• Good for CPU-heavy operations

• Avoid with:

o small collections

o mutable shared data

o I/O tasks

o ordered operations

9. Common Use Cases

• Convert Entity → DTO (map())

• Count/group/summarize ([Link])

• Remove duplicates (distinct)

• Pagination (skip/limit)

• Aggregation (reduce)
Most Frequently Asked Interview Questions (With Answers)

(Asked in 90% Java backend interviews)

What is the difference between map() and flatMap()?

Answer:

• map() transforms each element into another object.

• flatMap() transforms and flattens nested structure.

Example:

List<List<Integer>> nums = ...

[Link]().flatMap(list -> [Link]());

flatMap() is used when the output is a single flattened stream.

What is lazy evaluation in Streams?

Answer:
Streams do not execute intermediate operations immediately.
They build a pipeline, and execution happens only when a terminal operation (collect, forEach,
reduce) is invoked.

This improves performance by avoiding unnecessary operations.

Difference between findFirst() and findAny()?

Answer:

• findFirst() → returns the first element (ordered stream)

• findAny() → returns any element (faster, especially in parallel streams)


Use findAny() for performance unless ordering matters.

What are the pitfalls of parallel streams?

Answer:

• Overhead for small collections

• Not safe for mutable shared variables

• Ordering is not guaranteed

• Bad for I/O operations


• Uses [Link] → may affect other parallel tasks

What is reduce()? Give an example.

Answer:
reduce() performs aggregation into a single result.

Example:

int sum = [Link]().reduce(0, Integer::sum);

Can a Stream be reused? Why?

Answer:
No.
Once a terminal operation runs → the stream is consumed and closed.
Reusing will throw IllegalStateException.

How do you handle checked exceptions in Stream API?

Answer:
Streams don't allow checked exceptions directly.
Solutions:

• Wrap inside try-catch

• Write a custom wrapper

• Use RuntimeException

Example:

[Link](x -> {

try { return method(x); }

catch(Exception e) { throw new RuntimeException(e); }

});

What is the difference between Collection API and Stream API?

Answer:

Collection API Stream API

Stores data Processes data

Mutable Mostly functional


Collection API Stream API

External iteration (for loop) Internal iteration

Can be reused Cannot be reused

What is short-circuiting in streams?

Answer:
Operations like anyMatch, findFirst, limit can stop the pipeline early—improving performance.

What does mapToInt() do and why is it useful?

Answer:
It converts Stream<Integer> → IntStream.
Benefits:

• Faster

• Uses primitive operations

• Has useful methods like .sum(), .average()


20 Java Stream API Coding Questions + Answers

Count frequency of characters in a string

String s = "banana";

Map<Character, Long> freq =

[Link]()

.mapToObj(c -> (char)c)

.collect([Link](c -> c, [Link]()));

Count frequency of words in a sentence

String s = "java is easy java is powerful";

Map<String, Long> wordFreq =

[Link]([Link](" "))

.collect([Link](w -> w, [Link]()));

Find the second highest number

int secondHighest =

[Link]()

.sorted([Link]())

.skip(1)

.findFirst()

.orElseThrow();

Find the second smallest number

int secondSmallest =

[Link]()

.sorted()
.skip(1)

.findFirst()

.orElseThrow();

Find duplicates in a list

Set<Integer> duplicates =

[Link]()

.filter(i -> [Link](list, i) > 1)

.collect([Link]());

Find unique elements

Set<Integer> unique =

[Link]()

.filter(i -> [Link](list, i) == 1)

.collect([Link]());

Remove duplicates from a list

List<Integer> uniqueList =

[Link]()

.distinct()

.collect([Link]());

Sort strings by length

List<String> sorted =

[Link]()

.sorted([Link](String::length))

.collect([Link]());

Sort employees by salary (Employee::getSalary)

List<Employee> sortedBySalary =

[Link]()
.sorted([Link](Employee::getSalary))

.collect([Link]());

Group employees by department

Map<String, List<Employee>> byDept =

[Link]()

.collect([Link](Employee::getDepartment));

Find highest paid employee

Employee highest =

[Link]()

.max([Link](Employee::getSalary))

.orElse(null);

Find lowest salaried employee

Employee lowest =

[Link]()

.min([Link](Employee::getSalary))

.orElse(null);

Convert List<Employee> → List<EmployeeDTO>

List<EmployeeDTO> dtos =

[Link]()

.map(e -> new EmployeeDTO([Link](), [Link](), [Link]()))

.collect([Link]());

Find first non-repeating character in a string

Character firstNonRepeat =

[Link]()

.mapToObj(c -> (char)c)

.collect([Link](c -> c, LinkedHashMap::new, [Link]()))


.entrySet().stream()

.filter(e -> [Link]() == 1)

.map([Link]::getKey)

.findFirst()

.orElse(null);

Reverse each word in a sentence

String result =

[Link]([Link](" "))

.map(w -> new StringBuilder(w).reverse().toString())

.collect([Link](" "));

Sum of all even numbers

int sum =

[Link]()

.filter(n -> n % 2 == 0)

.mapToInt(n -> n)

.sum();

Find longest string in a list

String longest =

[Link]()

.max([Link](String::length))

.orElse(null);

Convert List<List<Integer>> to List<Integer> (Flattening)

List<Integer> flat =

[Link]()

.flatMap(List::stream)

.collect([Link]());
Partition numbers into even and odd

Map<Boolean, List<Integer>> partition =

[Link]()

.collect([Link](n -> n % 2 == 0));

Count how many employees earn > 50,000

long count =

[Link]()

.filter(e -> [Link]() > 50000)

.count();

You might also like