Junior — Middle
What are the differences between using Stream API and regular collections for data processing in Java?
sobes.tech AI
Answer from AI
Stream API in Java provides a declarative way to process collections, allowing for more readable and concise code. Main differences from regular collections:
- Lazy evaluation: Stream operations (except terminal ones) are performed lazily, meaning they are computed only when necessary.
- Parallelism: Stream API easily allows parallel operations, which is difficult to implement with regular collections.
- Functional style: Stream uses lambda expressions and functional interfaces, simplifying transformation chains.
- Immutability: Stream does not modify the original collection but returns a new data stream.
Example of using Stream for filtering and transforming a list:
List<String> names = Arrays.asList("Anna", "Bob", "Charlie", "David");
List<String> filtered = names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());
Unlike this, regular collections require explicit loops and conditions for similar operations.