Junior — Middle
How do approaches to collection processing differ when using standard loops and Stream API in Java?
sobes.tech AI
Answer from AI
Standard loops (for, while) in Java are an imperative approach to processing collections, where the programmer explicitly controls iteration and state. Such code is often more detailed and less declarative.
The Stream API offers a declarative style: you describe what you want to do with the collection elements (filtering, transforming, aggregating), rather than how exactly to do it. The Stream API supports lazy evaluation and can easily utilize parallelism.
Example with a loop and Stream API:
List<String> names = Arrays.asList("Anna", "Bob", "Charlie");
// Standard loop
List<String> filtered = new ArrayList<>();
for (String name : names) {
if (name.length() > 3) {
filtered.add(name.toUpperCase());
}
}
// Stream API
List<String> filteredStream = names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());
The Stream API improves readability and makes it easy to combine operations, as well as to use parallel streams for performance enhancement.