Junior — Middle
Explain what the Stream API in Java is and how it is used when working with data collections.
sobes.tech AI
Answer from AI
Stream API in Java is a powerful tool for working with collections and other data sources, introduced in Java 8. It allows writing declarative and functional code for processing sequences of elements.
Main features of Stream API:
- Filtering elements (
filter) - Transforming elements (
map) - Sorting (
sorted) - Aggregation (e.g.,
reduce,count,collect)
Example of using Stream API for filtering and transforming a list of strings:
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");
List<String> filteredNames = names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
System.out.println(filteredNames); // [CHARLIE, DAVID]
}
}
Stream API allows writing compact and readable code for data processing without explicit loops, enhancing expressiveness and convenience when working with collections.