Junior — Middle
What are the differences between using data streams and regular loops in programming?
sobes.tech AI
Answer from AI
Differences between using data streams (Streams) and traditional loops in programming:
- Imperative vs declarative style: Loops are an imperative approach, where the iteration process is explicitly described. Data streams are declarative, describing what needs to be obtained.
- Readability and conciseness: Streams allow writing more compact and expressive code.
- Parallelism capability: Streams can easily switch to parallel mode (
parallelStream()), simplifying parallel processing. - Lazy execution: Operations in streams are performed lazily, only when necessary.
- Functional operations: Streams support filtering, mapping, sorting, and other operations as a chain of calls.
Example in Java:
// Traditional loop
List<String> names = Arrays.asList("Anna", "Bob", "Carol");
List<String> filtered = new ArrayList<>();
for (String name : names) {
if (name.startsWith("A")) {
filtered.add(name.toUpperCase());
}
}
// Using streams
List<String> filteredStream = names.stream()
.filter(name -> name.startsWith("A"))
.map(String::toUpperCase)
.collect(Collectors.toList());