Junior
What is the main idea of Stream API in Java?
sobes.tech AI
Answer from AI
The main idea of the Stream API is to provide a declarative way to process collections of data. Instead of an imperative iterative approach with explicit control of loops and states, streams allow you to describe what needs to be done with the data (filtering, transforming, aggregating), leaving the implementation of how to do it to the API.
Key concepts:
- Immutability: Streams do not modify the original data source. Stream operations create new streams or results.
- Laziness: Many stream operations, such as
filter()andmap(), are intermediate. They are not executed until a terminal operation, such ascollect()orforEach(), is invoked. This allows for optimization of execution. - Pipelining: Stream operations can be combined into a pipeline. Each element passes through the pipeline sequentially or in parallel.
- Parallel processing: Streams are designed with the ability for easy parallel data processing, often with minimal code changes (
parallelStream()).
Advantages:
- More readable and expressive code for complex collection operations.
- Ease of parallelization.
- Elimination of boilerplate code related to iteration.
// Example: Filtering and transforming a list of strings
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
List<Integer> lengths = names.stream()
.filter(name -> name.startsWith("A")) // Intermediate operation
.map(String::length) // Intermediate operation
.collect(Collectors.toList()); // Terminal operation
// lengths will contain [5]