📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
Stream API is one of the most powerful features introduced in Java 8. It allows you to work with collections in a declarative, functional way by chaining operations like filtering, mapping, and reducing.
In this article, we’ll dive into the top 10 Java Stream API interview questions and answers asked in 2025.
1️⃣ What is Java Stream API and Why is it Useful?
Java Stream API allows you to process data from collections in a fluent, readable, and functional style. Instead of writing for-loops and handling data manually, you can describe what needs to be done using a pipeline of operations like map()
, filter()
, and collect()
.
Streams also support lazy evaluation, parallel processing, and method chaining, which makes code cleaner and faster to execute. For example, if you want to get all employee names earning more than ₹50,000:
employees.stream()
.filter(e -> e.getSalary() > 50000)
.map(Employee::getName)
.collect(Collectors.toList());
2️⃣ What is the Difference Between Intermediate and Terminal Operations?
In the Stream API, operations are divided into two categories:
- intermediate operations
- terminal operations
Intermediate operations return another stream, allowing you to chain more methods. These are lazy, meaning they don’t execute until a terminal operation is invoked.
Terminal operations end the pipeline and produce a result such as a list, a count, or even just a side effect. Without a terminal operation, the stream pipeline won’t run at all.
Here is the table that contains differences between Java 8 Stream Intermediate Vs Terminal Operations:

3️⃣ How is map()
Different from flatMap()
?
Use map()
when you want to transform individual elements in a stream. Use flatMap()
when each element itself is a collection or stream, and you want to flatten it into one combined stream.

Java Example: map() vs flatMap()
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
// List of sentences
List<String> sentences = Arrays.asList("Java Stream", "map vs flatMap", "Core Concepts");
// Using map(): Each sentence becomes a list of words (nested list)
List<List<String>> mapped = sentences.stream()
.map(sentence -> Arrays.asList(sentence.split(" ")))
.collect(Collectors.toList());
System.out.println("Using map():");
System.out.println(mapped); // Output: [[Java, Stream], [map, vs, flatMap], [Core, Concepts]]
// Using flatMap(): All words are flattened into one list
List<String> flatMapped = sentences.stream()
.flatMap(sentence -> Arrays.stream(sentence.split(" ")))
.collect(Collectors.toList());
System.out.println("\nUsing flatMap():");
System.out.println(flatMapped); // Output: [Java, Stream, map, vs, flatMap, Core, Concepts]
}
}

4️⃣ What is the Use of the filter()
Method in Streams?
The filter()
method is used to keep only those elements that satisfy a given condition. It’s a powerful way to apply logic directly to a stream without needing an if-condition or manual removal.
For example, if you want only the even numbers from a list, you can write:
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
This keeps your code readable and focused on the what, not the how.
5️⃣ What is the Difference Between collect()
and toList()
?
The collect()
method is a terminal operation used to convert a stream into a collection like List
, Set
, or Map
using collectors provided by the Collectors
utility class. It offers flexibility and supports various operations like grouping, partitioning, joining, and summing.
The toList()
method, introduced in Java 16, is a more concise alternative to collect(Collectors.toList())
. It creates an unmodifiable list, which is ideal when you just need to collect stream results without any further modifications.

6️⃣ What Does reduce()
Do in a Java Stream?
The reduce()
method is used to combine stream elements into a single value using a binary operation. You define an identity value and a function, and the stream applies that function cumulatively to the elements.
It’s great for calculations like summing numbers, multiplying them, or creating comma-separated strings. For example:
int total = numbers.stream().reduce(0, Integer::sum);
This will return the sum of all the integers in the list.
7️⃣ What is Lazy Evaluation in Java Streams?
Lazy evaluation means that stream operations are not executed immediately when the stream is created. Instead, intermediate operations are stored and only run when a terminal operation is called.
This improves performance, especially when working with large datasets, because unnecessary operations can be skipped. For example, this does nothing:
Stream<String> stream = list.stream().filter(s -> s.length() > 5);
But when you add a terminal operation:
stream.collect(Collectors.toList());
Only then is the filter condition applied.
8️⃣ How Can You Sort a List Using Streams?
Streams offer a convenient way to sort collections using the sorted()
method. You can sort elements naturally or define your own custom comparator.
For example, to sort names alphabetically:
list.stream().sorted().collect(Collectors.toList());
To sort employees by salary:
employees.stream()
.sorted(Comparator.comparing(Employee::getSalary))
.collect(Collectors.toList());
9️⃣ How to Remove Duplicates Using Streams?
Duplicates can be removed from a stream using the distinct()
method. It ensures that only unique elements are passed to the next stage of the stream pipeline.
For example:
List<String> names = List.of("Ravi", "Ravi", "Sita", "Geeta");
List<String> uniqueNames = names.stream().distinct().collect(Collectors.toList());
This results in: ["Ravi", "Sita", "Geeta"]
.
🔟 What are Parallel Streams and When Should You Use Them?
Parallel streams split the data into multiple chunks and process them in parallel using multiple threads. This can boost performance for large data processing tasks.
You should use parallelStream()
when the operations are independent, stateless, and CPU-intensive. But be cautious—parallel streams may reduce performance for small data sets or IO-bound tasks.
list.parallelStream()
.map(String::toUpperCase)
.collect(Collectors.toList());
11. How to Create Streams in Java?
Java provides several ways to create streams depending on your data source. You can create streams from collections, arrays, individual values, or even from file/data generators.
✅ Example: Different Ways to Create Streams:
// 1. From a List or Set
List<String> names = List.of("Ravi", "Sita", "Amit");
Stream<String> stream1 = names.stream();
// 2. From an Array
String[] fruits = {"Apple", "Banana", "Mango"};
Stream<String> stream2 = Arrays.stream(fruits);
// 3. Using Stream.of()
Stream<Integer> stream3 = Stream.of(10, 20, 30);
// 4. Using Stream.builder()
Stream<String> stream4 = Stream.<String>builder()
.add("One").add("Two").add("Three")
.build();
// 5. Using Stream.generate() (infinite stream)
Stream<Double> stream5 = Stream.generate(Math::random).limit(5);
// 6. Using Stream.iterate() (infinite stream with pattern)
Stream<Integer> stream6 = Stream.iterate(1, n -> n + 2).limit(5);
// 7. From Files (using NIO)
Stream<String> lines = Files.lines(Path.of("data.txt"));
Each method serves a different purpose. For example, Stream.generate()
and Stream.iterate()
are best for infinite sequences, while Stream.of()
is great for quick static values.
12. Collections vs Streams
13. What does the Stream map() function do? why you use it?
The map() function is an intermediate function that is used to perform map functional operations in Java. This means it can transform one type of object into another by applying a function.Use the map() function to convert one object to another object.
For example, if you have a list of strings and want to convert it to a list of integers, you can use map() to do so.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main
{
public static void main(String[] args)
{
List<String> listOfStrings = Arrays.asList("1", "2", "3", "4", "5");
List<Integer> listOfIntegers = listOfStrings.stream()
.map(Integer::valueOf)
.collect(Collectors.toList());
System.out.println(listOfIntegers);
}
}
Output:
[1, 2, 3, 4, 5]
14. What does the Stream filter() method do? when you use it?
Example 1: Using the filter() method to filter a List of string objects:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Tester {
public static void main(String[] args){
List<String> lines = Arrays.asList("java", "c", "python");
List<String> result = lines.stream() // convert list to stream
.filter(line -> !"c".equals(line)) // we dont like c
.collect(Collectors.toList()); // collect the output and convert streams to a List
result.forEach(System.out::println);
}
}
Output:
java
python
Let's first create a Product class:
class Product { private int id; private String name; private float price; // getters and setters }
public class StreamFilterExample { public static void main(String[] args) { // using stream API List < Product > filteredProducts = getProducts().stream() .filter((product) -> product.getPrice() > 25000 f) .collect(Collectors.toList()); filteredProducts.forEach(System.out::println); } private static List < Product > getProducts() { List < Product > productsList = new ArrayList < Product > (); productsList.add(new Product(1, "HP Laptop", 25000 f)); productsList.add(new Product(2, "Dell Laptop", 30000 f)); productsList.add(new Product(3, "Lenevo Laptop", 28000 f)); productsList.add(new Product(4, "Sony Laptop", 28000 f)); productsList.add(new Product(5, "Apple Laptop", 90000 f)); return productsList; } }In the above example, we are using the filter() method to filter products whose price is greater than 25k:
List < Product > filteredProducts = getProducts().stream() .filter((product) -> product.getPrice() > 25000 f) .collect(Collectors.toList());
15. What does the Stream flatmap() function do? why you need it?
To understand what flattening a stream consists in, consider a structure like [ [1,2,3],[4,5,6],[7,8,9] ] which has "two levels". It's basically a big List containing three more List. Flattening this means transforming it in a "one level" structure e.g. [ 1,2,3,4,5,6,7,8,9 ] i.e. just one list.
For example, In the below program, you can see that we have three lists merged into one using a flatMap() function.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args)
{
List<Integer> evens = Arrays.asList(2, 4, 6);
List<Integer> odds = Arrays.asList(3, 5, 7);
List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11);
List<Integer> numbers = Stream.of(evens, odds, primes)
.flatMap(list -> list.stream())
.collect(Collectors.toList());
System.out.println("flattend list: " + numbers);
}
}
flattend list: [2, 4, 6, 3, 5, 7, 2, 3, 5, 7, 11]
Comments
Post a Comment
Leave Comment