Java 8 Interview Masterclass
How interviewers think — core, Stream, Optional, functional interface, parallel, collector, method reference and internals questions, plus output-based puzzles.
#Introduction
The previous chapters covered how Java 8 works. This chapter is about how interviewers think.
Companies like TCS Digital, Infosys (Specialist Programmer), Accenture, Capgemini, Deloitte, Cognizant, IBM, Oracle, JPMorgan Chase, Goldman Sachs, Walmart and Amazon usually don't ask "What is the Stream API?" Instead they ask:
- "Why did Java introduce Streams?"
- "Why can't a Stream be reused?"
- "When would
parallelStream()make performance worse?"
The goal is to answer these confidently.
#Core Java 8 Questions
Q1Why was the Stream API introduced?
Before Java 8:
for (Employee e : employees) {
if (e.getSalary() > 50000) {
System.out.println(e.getName());
}
}Problems: too much boilerplate, hard to parallelize, external iteration.
Streams introduced: functional programming, internal iteration, lazy evaluation, easy parallel processing and cleaner code.
Q2Difference between Collection and Stream?
| Collection | Stream |
|---|---|
| Stores data | Processes data |
| Can be reused | Single use |
| Eager | Lazy |
| Mutable | Doesn't modify the source |
Q3Why are Streams lazy?
Because Java delays execution until it knows exactly what result is required. Benefits: better performance, pipeline optimization and short-circuiting.
Q4Why can't Streams be reused?
Stream<String> stream = names.stream();
stream.count();
stream.count(); // IllegalStateExceptionA Stream represents a one-time traversal of a data source.
Q5Difference between intermediate and terminal operations?
| Intermediate | Terminal |
|---|---|
filter, map, sorted, distinct, limit, skip | collect, reduce, count, max, min, forEach, findFirst |
| Lazy — return a new Stream | Trigger execution and consume the stream |
#Stream Questions
Q6Difference between map() and flatMap()?
Q7Difference between filter() and map()?
| filter() | map() |
|---|---|
| Removes elements | Transforms elements |
Takes a Predicate (returns boolean) | Takes a Function (returns a new value) |
Q8Difference between reduce() and collect()?
reduce(): many → one (sum, max, min).collect(): many → collection.
Q9Difference between findFirst() and findAny()?
findFirst()returns the first element and respects encounter order.findAny()returns any matching element and is faster in parallel streams.
Q10Difference between sorted() and max()?
Need only the maximum? Use max(), not sorted().findFirst(). max() is O(n); sorting is O(n log n).
#Optional Questions
Q11Difference between of() and ofNullable()?
| of() | ofNullable() |
|---|---|
Doesn't allow null | Allows null |
Q12Difference between orElse() and orElseGet()?
The most asked Optional question.
orElse()— its argument is always evaluated, even if a value is present.orElseGet()— the supplier runs only if the Optional is empty.
Q13Why avoid Optional.get()?
Because it throws NoSuchElementException. Prefer orElse(), orElseThrow() or ifPresent().
#Functional Interface Questions
Q14What is a functional interface?
An interface with exactly one abstract method — e.g. Predicate, Function, Consumer, Supplier.
Q15Difference between Predicate and Function?
| Predicate | Function |
|---|---|
Returns boolean | Returns any object |
Q16Difference between Supplier and Consumer?
Supplier produces; Consumer consumes.
#Parallel Stream Questions
Q17When should we use parallelStream()?
CPU-intensive work, large collections and independent operations.
Q18When should we NOT use parallelStream()?
Avoid it for database calls, REST API calls, small collections and shared mutable objects.
Q19Which thread pool is used?
ForkJoinPool.commonPool().
Q20Difference between forEach() and forEachOrdered()?
forEach()— no order guarantee.forEachOrdered()— maintains encounter order.
#Collectors Questions
Q21Difference between groupingBy() and partitioningBy()?
groupingBy()— unlimited groups.partitioningBy()— onlytrueandfalse.
Q22Difference between toList() and collectingAndThen()?
collectingAndThen() allows a finishing transformation — e.g. List → immutable List.
Q23What is a Collector?
An object that knows how to create, accumulate, combine and finish results.
#Method Reference Questions
Q24Types of method references?
| Type | Example |
|---|---|
| Static | Integer::sum |
| Instance (specific object) | printer::print |
| Instance (arbitrary object) | String::length |
| Constructor | Employee::new |
#Primitive Stream Questions
Q25Why IntStream?
It avoids boxing and unboxing.
Q26Stream<Integer> vs IntStream?
The primitive stream is faster and has numeric methods like sum() and average().
#Internal Questions
Q27What is a Spliterator?
Iterator + splitter. Used internally for parallel streams.
Q28Why are Streams efficient?
Because of lazy evaluation, pipeline fusion and short-circuiting.
#Output-Based Questions
Q29What does this print?
List<Integer> list = Arrays.asList(1, 2, 3, 4);
list.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * 2)
.forEach(System.out::println);4
8Q30What is the return type?
Stream.of("A", "B", "C")
.findFirst();Optional<String>.
Q31What does IntStream.range(1, 5) print?
IntStream.range(1, 5)
.forEach(System.out::println);1
2
3
4Q32What does IntStream.rangeClosed(1, 5) print?
1
2
3
4
5#Top 30 Coding Questions Asked in Interviews
- First non-repeating character
- Duplicate characters
- Character frequency
- Word frequency
- Second highest salary
- Nth highest salary
- Highest salary by department
- Average salary by department
- Youngest employee by department
- Oldest employee by department
- Count employees by department
- Partition employees by salary
- Group employees by age
- Sort employees by salary
- Find duplicate numbers
- Remove duplicates
- Longest string
- Shortest string
- Top 3 salaries
- Reverse words
- Group anagrams
- Count vowels
- Prime numbers
- Fibonacci
- Flatten nested lists
- Merge two lists
- Sum all numbers
- Max/min salary
- Join strings
- Convert List → Map
#Senior Interview Questions
Q33Why does this fail?
List<Integer> list = new ArrayList<>();
IntStream.rangeClosed(1, 100)
.parallel()
.forEach(list::add);ArrayList is not thread-safe — multiple threads add at once.
Q34Why does this work?
.parallel()
.collect(Collectors.toList())Because collectors safely combine partial results.
Q35map() vs flatMap() in one line?
One → one vs one → many.
Q36reduce() vs Collectors.reducing()?
One is part of the Stream API; the other is part of the Collector API (used as a downstream collector).
#5+ Years Rapid Fire
| Question | One-line answer |
|---|---|
| Why Streams? | Functional, lazy data processing |
| Why Optional? | Avoid null and make absence explicit |
| Why functional interfaces? | Enable lambdas |
| Why method references? | Cleaner lambda syntax |
| Why IntStream? | Avoid boxing/unboxing |
| Why Spliterator? | Parallel traversal |
| Why lazy evaluation? | Better performance |
| Why parallel streams? | CPU-bound parallelism |
| Why groupingBy()? | SQL-like grouping |
| Why flatMap()? | Flatten nested collections |
#Where to Go Next
Java 8 is only one part of a 5+ years Java interview. Natural next topics:
- Advanced Java: concurrency and multithreading, the JVM memory model, garbage collection, reflection, advanced generics, serialization, collections internals,
ComparablevsComparator,equals()/hashCode(), immutable objects, design patterns, memory leaks, performance tuning and the JIT compiler. - Spring Boot: Spring Core, Boot internals, dependency injection, AOP, Spring Security + JWT, JPA/Hibernate internals, transactions, microservices, Kafka, Redis, Docker and Kubernetes.
- Daily coding practice: Streams + DSA + SQL.
#Chapter Summary
- Core "why" questions — Streams, laziness, single use
- Stream, Optional and functional interface comparisons
- Parallel stream and collector questions
- Method references, primitive streams and internals
- Output-based questions and the top 30 coding problems