Java 8 Stream Interview Questions: 22 Q&A From Beginner to Advanced
-
Last Updated:
-
By: Suraj S R
-
Series

Java 8 stream interview questions: lambdas, map vs flatMap, collectors, Optional, parallel streams. 22 Q&A from beginner to advanced, with runnable code.
Java 8 changed the way we write everyday Java code. Streams and lambdas now sit in almost every backend project. Because of that, java 8 stream interview questions come up in nearly every Java interview today. This guide gives you 22 questions, grouped from beginner to advanced.
I have sat on both sides of the table, as a candidate and as an interviewer. The pattern is always the same. Interviewers rarely want the textbook line. Instead, they want to see that you understand the why behind each operation. So every answer below is written the way you would actually speak it in the room.
Each answer also goes a little deeper than a one-liner. You get the reasoning, the common follow-up, and a short runnable snippet. If you are still covering the basics, start with the Core Java interview questions for freshers guide first. Let us start simple and build up slowly.
Answer – A lambda expression is a short block of code that you pass around like a value. Before Java 8, passing behaviour meant writing a full anonymous inner class. That was a lot of boilerplate for one line of logic. A lambda cuts that noise and keeps only the logic that matters.
Think of a lambda as a method without a name. It has three parts. There are the parameters, then an arrow, then the body. The compiler fills in the rest from the surrounding context.
// Old way - anonymous class
Runnable r1 = new Runnable() {
public void run() {
System.out.println("Running");
}
};
// Java 8 way - lambda
Runnable r2 = () -> System.out.println("Running");Why does this matter so much? Lambdas made the Stream API possible. Every stream method takes behaviour as an argument. Without lambdas, that code would be painful to read. So lambdas are not just shorter. They changed the whole style of modern Java.
A lambda can also capture variables from around it. But those variables must be effectively final. In plain words, you cannot change them after the lambda reads them. This keeps the captured value safe across threads.
| 💡 Interview insight A common follow-up is “can a lambda use local variables?” Yes, but only effectively final ones. Say that line and you earn an easy extra point. |
Answer – A functional interface is an interface with exactly one abstract method. That one method is the slot a lambda fills. Runnable, Callable, and Comparator are all functional interfaces. The whole Stream API is built on them.
People call that single method the SAM, short for Single Abstract Method. When you write a lambda, you are really writing the body of that SAM. The compiler matches your lambda to it by shape, not by name.
The @FunctionalInterface annotation is optional. Still, it is a healthy habit. It tells the compiler to fail the build if someone adds a second abstract method later. So it locks the contract and stops silent mistakes.
@FunctionalInterface
interface Calculator {
int operate(int a, int b);
}
Calculator add = (a, b) -> a + b;
System.out.println(add.operate(5, 3)); // 8A functional interface can still hold more methods. It can have default and static methods freely. Those do not count as abstract, so the single-method rule stays safe. Comparator is a good example, with default methods like reversed() and thenComparing().
| 💡 Interview insight Interviewers love this trap: is an interface with one abstract method plus two default methods still functional? Yes, it is. Default methods never break the rule. |
Answer – Java 8 added a package called java.util.function. It ships ready-made functional interfaces, so you rarely need to write your own. Four of them cover most daily work.
Here is an easy way to remember them. Function takes and returns. Predicate takes and tests. Consumer takes and acts. Supplier gives without taking.
Function<String, Integer> length = s -> s.length();
Predicate<Integer> isEven = n -> n % 2 == 0;
Consumer<String> printer = s -> System.out.println(s);
Supplier<Double> random = () -> Math.random();
System.out.println(length.apply("hello")); // 5
System.out.println(isEven.test(4)); // trueThe family is actually much larger. BiFunction takes two inputs. UnaryOperator returns the same type it takes. There are also primitive versions like IntPredicate and ToIntFunction. These avoid autoboxing and run faster on numbers.
Once these names click, the Stream API reads like plain English. filter wants a Predicate. map wants a Function. forEach wants a Consumer. So the method signature itself tells you what to pass.
Answer – A method reference is a shortcut for a lambda that only calls one existing method. Instead of s -> s.toUpperCase(), you write String::toUpperCase. It reads cleaner and shows your intent faster. The :: symbol is the method reference operator.
Reach for it only when the lambda just forwards its argument. If the lambda does extra work, a normal lambda stays clearer. So a method reference is about saying the same thing with less ceremony.
There are four forms, and naming all four looks sharp in an interview.
List<String> names = Arrays.asList("ravi", "sita", "arjun");
// Lambda
names.forEach(n -> System.out.println(n));
// Method reference - same thing, cleaner
names.forEach(System.out::println);The third form confuses many people. ClassName::instanceMethod looks static, but it is not. The first argument becomes the object the method runs on. So String::toUpperCase really means element.toUpperCase() for each element in the stream.
Answer – Think of a stream as a pipeline for processing data, not a place to store it. A collection holds elements in memory. In contrast, a stream just carries them through a sequence of operations. That single idea is the core difference. One stores, the other processes.
Here are the differences worth saying out loud.
List<String> names = Arrays.asList("ravi", "sita", "arjun", "sita");
long count = names.stream()
.filter(n -> n.length() == 4)
.count();
System.out.println(count); // 3One more point scores well. A collection is eager, so an element sits in memory the moment you add it. A stream is lazy, so it waits until a terminal operation asks for a result. Because of that, a stream can even describe an infinite sequence without filling memory.
Also, a stream never touches its source. The filter above removes nothing from the list. It only skips elements as data flows past. So the original collection stays safe and unchanged.
Answer – There are several ways, and interviewers like hearing more than one. The most common way is calling stream() on a collection. But you can also build a stream from values, arrays, files, or even an infinite generator.
// From a collection
List<Integer> list = Arrays.asList(1, 2, 3);
Stream<Integer> s1 = list.stream();
// From values
Stream<String> s2 = Stream.of("a", "b", "c");
// From an array
int[] arr = {1, 2, 3};
IntStream s3 = Arrays.stream(arr);
// Infinite stream, bounded with limit()
Stream<Integer> s4 = Stream.iterate(0, n -> n + 2).limit(5);A few of these deserve a note. Stream.of is handy for quick tests. Stream.iterate and Stream.generate build infinite streams, so you must bound them with limit(). Otherwise the pipeline never ends.
For primitive values, prefer IntStream, LongStream, and DoubleStream. They skip autoboxing, so they run faster and use less memory. They also add handy methods like sum() and average() that object streams lack.
Even files fit in. Files.lines() gives you a stream of lines from a text file. So streams are not only for lists. They work across many data sources.
Answer – Both are intermediate operations, yet they do very different jobs. The filter() method decides which elements stay. The map() method changes what each element looks like. So filter is about selection, while map is about transformation.
filter() takes a Predicate and returns true or false for each element. Only the true ones move forward. map() takes a Function and swaps each element for a new value. Because of that, the element count can drop after filter. It never changes after map.
List<String> names = Arrays.asList("ravi", "sita", "arjun");
// Selection - some elements may be dropped
List<String> longNames = names.stream()
.filter(n -> n.length() > 4)
.collect(Collectors.toList()); // [arjun]
// Transformation - count stays the same
List<Integer> lengths = names.stream()
.map(String::length)
.collect(Collectors.toList()); // [4, 4, 5]There is also a type difference that interviewers like. map can change the element type. A stream of String can become a stream of Integer after map. filter never changes the type. It only keeps or drops the same elements.
| 💡 Interview insight A clean one-liner to remember: filter changes how many, map changes what. You often chain them — filter the rows you want, then map them into the shape you need. |
Answer – A stream pipeline has two kinds of operations. Intermediate operations build the pipeline and return a new stream. Terminal operations trigger the work and produce a result. Importantly, nothing actually runs until the terminal operation is called.

How do you tell them apart at a glance? Just check the return type. If a method returns a Stream, it is intermediate. If it returns a value, a List, or nothing, it is terminal. That one rule covers almost every case.
Stream<String> pipeline = Stream.of("ravi", "sita")
.filter(n -> n.startsWith("r")); // nothing runs yet
long count = pipeline.count(); // now the pipeline runs
System.out.println(count); // 1A pipeline can have many intermediate steps but only one terminal step. After the terminal runs, the stream is finished. So the shape stays simple. You stack cheap intermediate steps, then end with one terminal step that does the real work. Figure 1 above shows this flow.
Answer – Lazy evaluation means a stream does no work until it has to. Intermediate operations only record what should happen. The real processing begins only when a terminal operation runs. As a result, the stream skips a lot of wasted effort.
Laziness also enables a smart trick. The stream pushes one element through the whole pipeline at a time. It does not finish filter for every element and then start map. So with limit() or findFirst(), it can stop as soon as it has enough.
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> first = nums.stream()
.peek(n -> System.out.println("checking: " + n))
.filter(n -> n % 2 == 0)
.findFirst();
// prints checking: 1, checking: 2 -- then stopsLook closely at the output. It stops at 2 and never touches 3, 4, or 5. That behaviour is called short-circuiting, and laziness makes it possible. On a large list, this can save a huge amount of work.
There is a deeper design reason too. Laziness lets the stream fuse operations together. filter and map then run in one pass over the data, not two. So the pipeline stays efficient even with many steps.
Answer – The map() method turns each element into exactly one new element. The flatMap() method turns each element into a whole stream of elements, then flattens all those streams into one. So map is one-to-one, while flatMap is one-to-many plus flattening.
The word flatten is the key. Say your mapper returns a list for each element. With map, you end up with a stream of lists, which stays nested. With flatMap, those inner lists merge into one single stream.
List<List<Integer>> nested = Arrays.asList(
Arrays.asList(1, 2),
Arrays.asList(3, 4),
Arrays.asList(5));
List<Integer> flat = nested.stream()
.flatMap(List::stream) // flattens the inner lists
.collect(Collectors.toList());
System.out.println(flat); // [1, 2, 3, 4, 5]The classic real example is splitting sentences into words. Each sentence breaks into many words. So map would give you a stream of arrays, which is awkward. flatMap merges every word into one clean stream.
List<String> sentences = Arrays.asList("hello world", "java streams");
List<String> words = sentences.stream()
.flatMap(s -> Arrays.stream(s.split(" ")))
.collect(Collectors.toList());
System.out.println(words); // [hello, world, java, streams]| 💡 Interview insight Ask yourself one question: does my mapper return one value or many? One value means map. A list, an array, or a stream means flatMap. That framing answers it instantly. |
Answer – Optional is a small box that may or may not hold a value. It was added to make null handling clear and safe. Instead of returning null and risking a NullPointerException, a method returns an Optional. The caller then has to handle the empty case.
Think of it as a label on a method. The return type now says the value might be missing. So the next developer cannot quietly forget to check. That is the real win, better than any clever trick.
Here is how to use it well.
Optional<String> name = Optional.of("ravi");
String result = name
.map(String::toUpperCase)
.orElse("UNKNOWN");
System.out.println(result); // RAVINow here is how you should not use it.
One line sums it up. Optional is a return type, not a field type. Use it at the boundary where a value might be absent. Do not spread it across your whole data model.
| 💡 Interview insight The sharpest answer names the anti-patterns too. Saying “Optional is for return types, not fields” signals real production experience. |
Answer – Both return one element wrapped in an Optional. The findFirst() method always returns the first element in order. The findAny() method can return any element, whichever is handy. On a normal sequential stream, they behave the same. The real difference appears with parallel streams.
Why wrap the result in Optional? Because the stream might be empty after filtering. So there may be no element to return at all. Optional handles that case cleanly, without a null.
In a parallel stream, findAny() is usually faster. It ignores order, so any thread can hand back its element at once. Meanwhile findFirst() must respect encounter order. That forces extra coordination between the threads.
List<String> names = Arrays.asList("ravi", "sita", "arjun");
Optional<String> any = names.parallelStream()
.filter(n -> n.length() == 4)
.findAny();
System.out.println(any.get());So the rule is simple. Pick findAny() when order does not matter and you want speed. Pick findFirst() when you truly need the first element in order.
Answer – The collect() method is a terminal operation that gathers stream elements into a result. The Collectors class then supplies ready-made recipes. Among them, toList, groupingBy, and partitioningBy are the three you will use most.
List<String> names = Arrays.asList("ravi", "sita", "arjun", "amit");
Map<Integer, List<String>> byLength = names.stream()
.collect(Collectors.groupingBy(String::length));
// {4=[ravi, sita, amit], 5=[arjun]}
Map<Boolean, List<String>> byStart = names.stream()
.collect(Collectors.partitioningBy(n -> n.startsWith("a")));
// {false=[ravi, sita], true=[arjun, amit]}The last two differ in one clear way. groupingBy can create many groups, one per distinct key. partitioningBy always creates exactly two, true and false. So partitioning is really a special two-way grouping.
groupingBy also accepts a second collector, called a downstream. That is how you count or sum inside each group. For example, you can group people by city, then count them per city, all in one line. So it is far more powerful than it first looks.
Answer – No, you cannot reuse a stream. A stream is a one-time pipeline. Once a terminal operation runs, the stream is closed for good. If you try to use it again, Java throws an IllegalStateException. This surprises many developers the first time.
Stream<String> s = Stream.of("a", "b", "c");
s.forEach(System.out::println); // works fine
s.count(); // IllegalStateExceptionWhy does Java work this way? A stream does not store its elements. It only pulls them from the source as needed. After one pass, there is nothing left to pull. So reusing it would have no data to work on.
The fix is easy. Keep the source collection and call stream() again whenever you need a fresh pass. So the collection stays reusable. The stream, by design, does not.
| 💡 Interview insight A neat trick for repeated pipelines is a Supplier<Stream<T>>. Call get() each time to build a brand-new stream from the same logic, without copying the code. |
Answer – You sort a stream with the sorted() operation. With no argument, it uses natural order. For a custom order, you pass a Comparator. And Comparator.comparing makes multi-field sorting very readable.
Natural order needs the elements to implement Comparable. Numbers and strings already do. For your own class, you either implement Comparable or pass a Comparator. Otherwise sorted() throws a ClassCastException at runtime.
List<String> names = Arrays.asList("ravi", "arjun", "amit");
// Natural order
names.stream().sorted().forEach(System.out::println);
// amit, arjun, ravi
// By length first, then alphabetically as a tie-breaker
List<String> sorted = names.stream()
.sorted(Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()))
.collect(Collectors.toList());The chaining style is the part interviewers like. comparingInt picks the first field. thenComparing adds a tie-breaker. reversed() flips the whole order. So you can express complex sorting in one clear line.
Keep one performance note in mind. sorted() is a stateful operation. It must see every element before it can emit the first one. So it can get costly on very large or parallel streams.
Answer – This is a favourite coding question. You count how many times each element appears using groupingBy with counting. The element becomes the key. The count becomes the value. One statement does most of the work.
List<String> items = Arrays.asList(
"apple", "banana", "apple", "mango", "banana", "apple");
Map<String, Long> frequency = items.stream()
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()));
System.out.println(frequency);
// {banana=2, apple=3, mango=1}Let me explain the two parts. Function.identity() means group by the element itself. Collectors.counting() is the downstream collector that counts each group. Together they build a frequency map in a single pass.
To find only duplicates, filter that map. Keep the entries where the count is more than one. So the very same pattern answers two common questions, frequency and duplicates.
List<String> duplicates = frequency.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println(duplicates); // [banana, apple]| 💡 Interview insight In payments work, this exact pattern catches duplicate transaction IDs inside a batch file. Naming a real use case shows the interviewer you have shipped this code. |
Answer – A sequential stream processes elements one by one on a single thread. A parallel stream splits the data and runs chunks on several threads. You switch it on with parallelStream() or .parallel(). Under the hood, it uses the common ForkJoinPool.
By default, that pool holds one thread less than the number of CPU cores. The main thread also joins in. So on an 8-core machine, you get about 8 workers together. That can speed up heavy, CPU-bound work on large data.
However, parallel streams often hurt. Watch out in these cases.
long count = IntStream.rangeClosed(1, 1_000_000)
.parallel()
.filter(n -> n % 2 == 0)
.count();There is one more trap worth naming. The common pool is shared across the whole JVM. So one slow parallel task can block every other one. In a web server, that can stall unrelated requests. For that reason, many teams avoid parallel streams in request-handling code.
| 💡 Interview insight Interviewers love “is parallel always faster?” Say no, firmly. Then explain that the common pool is shared, so one heavy task can choke the entire application. |
Answer – The reduce() method combines all elements of a stream into a single result. Think of summing numbers or joining strings. It can take up to three parts. These are an identity, an accumulator, and a combiner. Each part has a clear and separate job.
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5);
int sum = nums.stream()
.reduce(0, (a, b) -> a + b);
System.out.println(sum); // 15
// Three-argument form, safe for parallel streams
int total = nums.parallelStream()
.reduce(0, (a, b) -> a + b, Integer::sum);Let me walk through the sum example. The identity is 0, so an empty stream returns 0. The accumulator adds each number to the running total. In a parallel run, the stream splits into chunks, each chunk reduces on its own, and the combiner adds the partial sums.
This is why the combiner must agree with the accumulator. If they disagree, the parallel and sequential runs give different answers. So a safe rule is to keep both doing the same kind of operation.
One caution stands out. reduce works correctly only when the operation is associative. Addition and multiplication are associative. Subtraction is not. So a parallel subtraction in reduce can quietly give wrong results.
Answer – Stateless operations handle each element on its own. map and filter are stateless, because they need no memory of other elements. Stateful operations, by contrast, must know about other elements to work. distinct, sorted, and limit fall in this group.
List<Integer> nums = Arrays.asList(5, 3, 5, 1, 3);
List<Integer> result = nums.stream()
.distinct() // stateful - remembers seen values
.sorted() // stateful - needs all elements first
.collect(Collectors.toList());
// [1, 3, 5]Why does this matter in interviews? Because of performance. A stateless operation flows freely through the pipeline. A stateful one often has to pause and gather data first. sorted may buffer the entire stream before it emits anything. distinct must remember every value it has already seen.
The cost grows in parallel streams. Stateful operations need coordination across threads. So they can cancel out the speed-up you hoped for. When a parallel stream feels slow, a stateful step is often the reason.
So keep the mental split clear. map and filter are cheap and flow-friendly. sorted, distinct, and limit carry hidden state. Use them with care on large data.
Answer – Many candidates say a lambda is just sugar for an anonymous class. That answer is wrong, and interviewers notice. A lambda does not create a new class file at compile time. Instead, the compiler emits a special invokedynamic bytecode instruction.
Here is what happens step by step. The compiler turns the lambda body into a private method. Then it leaves an invokedynamic call where the lambda sits. At runtime, that call asks a bootstrap method for a function object.
That bootstrap method is LambdaMetafactory. It builds the object the first time the lambda runs. After that, the JVM links the call site and reuses it. So later calls stay fast and allocate nothing extra for a non-capturing lambda.
Runnable r = () -> System.out.println("hi");
// Compiles to an invokedynamic call site,
// not a separate Main$1.class file.Why did the designers choose this path? Flexibility and speed. invokedynamic lets the JVM decide the strategy at runtime. An anonymous class, on the other hand, locks a separate .class file at compile time. So lambdas stay lighter and give the JVM more room to optimise.
The line to remember is short. An anonymous class means a new class file. A lambda means an invokedynamic call site. That single detail sets you apart from most candidates.
Answer – A Collector describes how to fold stream elements into a result. The built-in ones cover most needs. Still, sometimes you want full control, so you build your own with Collector.of. It has four parts. These are a supplier, an accumulator, a combiner, and a finisher.
Collector<String, StringBuilder, String> joiner =
Collector.of(
StringBuilder::new, // supplier
(sb, s) -> sb.append(s).append(","), // accumulator
StringBuilder::append, // combiner
StringBuilder::toString); // finisher
String out = Stream.of("a", "b", "c").collect(joiner);
System.out.println(out); // a,b,c,It helps to connect this to reduce. A Collector is like a reduce with a mutable container. The supplier makes that container, such as a StringBuilder or a list. The accumulator keeps adding into the same container. So it avoids creating a new object per element, which is faster.
The combiner matters only for parallel streams. It merges two partial containers into one. The finisher then runs once at the end. It can convert the container into the final type, like turning a StringBuilder into a String.
Most of the time, stick to Collectors.joining or groupingBy. Write a custom Collector only when the built-ins truly cannot express your logic. So treat it as a last resort, not a first choice.
Answer – This is a classic stream coding question. You sort salaries in descending order, remove duplicates, skip the top one, and take the next. The distinct step handles ties, so two people on the same top salary do not break the result.
List<Integer> salaries = Arrays.asList(1000, 2000, 2000, 1500, 3000);
Optional<Integer> secondHighest = salaries.stream()
.distinct() // remove duplicate salaries
.sorted(Comparator.reverseOrder()) // highest first
.skip(1) // skip the top one
.findFirst(); // take the next
System.out.println(secondHighest.get()); // 2000Let me explain each step in order. distinct() removes repeated salary values. sorted(Comparator.reverseOrder()) puts the highest first. skip(1) drops the top salary. Then findFirst() returns the next one, which is the second highest.
The distinct() step is the one people forget. Without it, two equal top salaries both count as the top. So skip(1) would still land on that same top value. Then your answer is wrong, and the interviewer will catch it.
This pattern also generalises nicely. Change skip(1) to skip(n – 1) and you get the Nth highest value. So one small tweak answers a whole family of questions.
| 💡 Interview insight In real payment reconciliation, the same skip-and-findFirst pattern finds the Nth largest transaction in a batch. Tie the answer to production and it lands better. |