Java 8 FAQ: Top Questions
4. What is the Stream API in Java 8 and why is it useful?
The Stream API introduced in Java 8 provides a powerful way to perform functional-style operations on collections of data. Streams allow you to process data declaratively without needing to write complex loops and conditions.
πΊοΈ Step-by-Step Instructions:
- Create a stream from a collection using
.stream()
or.parallelStream()
. - Apply intermediate operations like
filter()
,map()
,sorted()
. - Terminate the stream with a terminal operation like
collect()
,forEach()
, orreduce()
.
π₯ Example Input:
List names = Arrays.asList("Alice", "Bob", "Alex");
List filtered = names.stream()
.filter(n -> n.startsWith("A"))
.collect(Collectors.toList());
π Expected Output:
[Alice, Alex]
β Java 8 Solution:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamExample {
public static void main(String[] args) {
List names = Arrays.asList("Alice", "Bob", "Alex");
List filtered = names.stream()
.filter(n -> n.startsWith("A"))
.collect(Collectors.toList());
System.out.println(filtered);
}
}
π Detailed Explanation:
- Streams are not data structures: They do not store data but convey data from a source through a pipeline of operations.
- Lazy Evaluation: Intermediate operations are evaluated only when a terminal operation is invoked.
- Parallelism: Streams support easy parallel processing with
parallelStream()
.
π οΈ Use Cases:
- Data filtering, transformation, and aggregation in collections.
- Writing cleaner, more expressive code for loops and data handling.
- Enabling parallel operations to improve performance.