1. What is Stream API in Java 8?
The Stream API is a feature introduced in Java 8 for processing collections of data in a functional and declarative way.
It allows developers to perform operations like filtering, mapping, sorting, and collecting data efficiently.
Key Features:
- Functional programming support
- Internal iteration
- Parallel processing
- Cleaner and shorter code
Example:
List<String> names = Arrays.asList("Ali", "Sara", "John");
names.stream()
.filter(name -> name.startsWith("S"))
.forEach(System.out::println);
Output:
Sara
Real-World Use Case:
In e-commerce applications, Stream API is used to filter active products, sort prices, and calculate totals.
2. Difference Between Collection and Stream
| Feature | Collection | Stream |
|---|---|---|
| Stores data | Yes | No |
| Modifies data | Yes | No |
| Iteration | External | Internal |
| Reusable | Yes | No |
| Processing style | Imperative | Functional |
Example:
List<Integer> list = Arrays.asList(1,2,3,4);
Stream<Integer> stream = list.stream();
Important Point:
A stream does not store elements. It only processes data from a source like a collection.
3. What are Intermediate Operations in Stream API?
Intermediate operations transform a stream into another stream.
These operations are lazy, meaning they execute only when a terminal operation is called.
Common Intermediate Operations:
- filter()
- map()
- sorted()
- distinct()
- limit()
Example:
List<String> names = Arrays.asList("Ram", "Shyam", "Ram");
names.stream()
.distinct()
.sorted()
.forEach(System.out::println);
4. What are Terminal Operations in Stream API?
Terminal operations produce a result or side effect.
Once a terminal operation is executed, the stream cannot be reused.
Common Terminal Operations:
- collect()
- forEach()
- count()
- reduce()
- findFirst()
Example:
long count = Arrays.asList(1,2,3,4,5)
.stream()
.count();
System.out.println(count);
5. What is the Difference Between map() and flatMap()?
map()
Transforms each element individually.
Example:
List<String> names = Arrays.asList("java", "spring");
List<String> upper = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
flatMap()
Flattens nested structures into a single stream.
Example:
List<List<String>> list = Arrays.asList(
Arrays.asList("A", "B"),
Arrays.asList("C", "D")
);
List<String> result = list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
Real-World Example:
Used in microservices when combining nested API response data into a single list.
6. What is filter() in Stream API?
The filter() method is used to select elements based on a condition.
Example:
List<Integer> numbers = Arrays.asList(10, 15, 20, 25);
numbers.stream()
.filter(n -> n > 15)
.forEach(System.out::println);
Output:
20
25
Use Case:
Filtering active users, successful transactions, or completed orders.
7. What is reduce() in Stream API?
reduce() combines all elements into a single result.
Example:
int sum = Arrays.asList(1,2,3,4)
.stream()
.reduce(0, Integer::sum);
System.out.println(sum);
Output:
10
Real-World Use Case:
Used for:
- Calculating total order amount
- Finding maximum salary
- Aggregating reports
8. What is collect() in Stream API?
collect() converts stream results into collections or other forms.
Example:
List<String> names = Arrays.asList("Java", "Spring");
List<String> result = names.stream()
.collect(Collectors.toList());
Common Collectors:
- toList()
- toSet()
- groupingBy()
- joining()
- counting()
9. What is the Difference Between findFirst() and findAny()?
| findFirst() | findAny() |
|---|---|
| Returns first element | Returns any element |
| Deterministic | Non-deterministic |
| Slower in parallel streams | Faster in parallel streams |
Example:
Optional<Integer> value =
Arrays.asList(1,2,3,4)
.stream()
.findFirst();
10. What is Optional in Java 8?
Optional is a container object used to avoid NullPointerException.
Example:
Optional<String> name = Optional.ofNullable(null);
System.out.println(name.orElse("Default"));
Output:
Default
Benefits:
- Avoids null checks
- Cleaner code
- Better readability
11. What is Lazy Evaluation in Stream API?
Operations are not executed until a terminal operation is invoked.
Example:
Stream.of("A", "B", "C")
.filter(x -> {
System.out.println(x);
return true;
});
Nothing prints because no terminal operation exists.
Why Important?
Improves performance by avoiding unnecessary computations.
12. What is Parallel Stream?
Parallel streams process data using multiple threads.
Example:
Arrays.asList(1,2,3,4,5)
.parallelStream()
.forEach(System.out::println);
Advantages:
- Faster processing for large datasets
- Better CPU utilization
Disadvantages:
- Thread overhead
- Not suitable for small data
13. Difference Between stream() and parallelStream()
| stream() | parallelStream() |
|---|---|
| Single thread | Multiple threads |
| Sequential processing | Parallel processing |
| Predictable order | Unpredictable order |
| Better for small tasks | Better for large tasks |
14. What is distinct() in Stream API?
distinct() removes duplicate elements.
Example:
Arrays.asList(1,2,2,3,3,4)
.stream()
.distinct()
.forEach(System.out::println);
Output:
1
2
3
4
15. What is sorted() in Stream API?
sorted() sorts elements naturally or using a comparator.
Example:
Arrays.asList(5,1,3,2)
.stream()
.sorted()
.forEach(System.out::println);
Custom Sorting:
names.stream()
.sorted((a,b) -> b.compareTo(a))
.forEach(System.out::println);
16. What is limit() in Stream API?
limit() restricts the number of elements.
Example:
Stream.of(1,2,3,4,5)
.limit(3)
.forEach(System.out::println);
Output:
1
2
3
Use Case:
Pagination APIs and dashboard results.
17. What is skip() in Stream API?
skip() ignores specified elements.
Example:
Stream.of(1,2,3,4,5)
.skip(2)
.forEach(System.out::println);
Output:
3
4
5
18. What is forEach() in Stream API?
forEach() performs an action on each element.
Example:
Arrays.asList("Java", "Spring")
.stream()
.forEach(System.out::println);
19. What is the Difference Between peek() and map()?
| peek() | map() |
|---|---|
| Used for debugging | Used for transformation |
| Does not modify data | Modifies data |
| Returns same stream | Returns transformed stream |
Example:
Arrays.asList(1,2,3)
.stream()
.peek(System.out::println)
.map(n -> n * 2)
.forEach(System.out::println);
20. Explain groupingBy() Collector
groupingBy() groups elements based on a condition.
Example:
Map<Integer, List<String>> result =
Arrays.asList("Java", "API", "Spring")
.stream()
.collect(Collectors.groupingBy(String::length));
System.out.println(result);
Real-World Use Case:
Grouping employees by department or students by grade.
21. Explain joining() Collector
joining() combines elements into a single string.
Example:
String result = Arrays.asList("Java", "Spring", "Boot")
.stream()
.collect(Collectors.joining(","));
System.out.println(result);
Output:
Java,Spring,Boot
22. How to Convert List to Map Using Streams?
Example:
Map<Integer, String> map =
Arrays.asList("Java", "Spring")
.stream()
.collect(Collectors.toMap(
String::length,
value -> value
));
23. Can We Reuse a Stream?
No. Once a terminal operation is called, the stream is closed.
Example:
Stream<String> stream = Stream.of("A", "B");
stream.forEach(System.out::println);
stream.forEach(System.out::println); // Exception
Exception:
java.lang.IllegalStateException
24. What is the Difference Between anyMatch(), allMatch(), and noneMatch()?
| Method | Meaning |
|---|---|
| anyMatch() | At least one matches |
| allMatch() | All must match |
| noneMatch() | No element should match |
Example:
boolean result = Arrays.asList(2,4,6)
.stream()
.allMatch(n -> n % 2 == 0);
25. What are the Advantages of Stream API?
Advantages:
- Cleaner code
- Better readability
- Functional programming support
- Easy parallel processing
- Reduced boilerplate code
Real-World Example:
Used heavily in:
- Spring Boot applications
- Microservices
- Data transformation layers
- REST API response processing