Junior — Middle
How to implement data stream processing using Stream API in Java?
sobes.tech AI
Answer from AI
The Stream API in Java allows working with data streams, providing a convenient and declarative way to process collections and other data sources. The main steps for working with streams:
- Creating a stream from a collection or array, e.g.,
list.stream(). - Applying intermediate operations (filter, map, sorted, etc.), which return a new stream and are not executed immediately.
- Applying a terminal operation (forEach, collect, reduce, etc.), which triggers processing and returns a result.
Example:
import java.util.*;
import java.util.stream.*;
public class StreamExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Anna", "Bob", "Charlie", "David");
// Get names longer than 3 characters, convert to uppercase, and print
names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.forEach(System.out::println);
}
}
This approach simplifies data processing, makes the code more readable, and allows easy parallelization of operations.