Java 8’s Stream API represents a significant shift from traditional iteration techniques for processing collections of data. Here’s a comparison of the two approaches:
Feature | Collections | Streams |
---|---|---|
Definition | In-memory data structure to store and manage data | Abstraction for processing data in a functional style |
Storage | Stores data elements | Does not store elements, just processes them |
Traversal | External iteration (e.g., for-loop, iterator) | Internal iteration (e.g., stream().forEach() ) |
Type | Eager (loads entire collection in memory) | Lazy (evaluated only when terminal operation is called) |
Modifiable | Can modify the underlying data | Cannot modify the source; results are computed |
Usage Purpose | For storing and managing data | For processing and transforming data |
Operations | Limited (add, remove, sort, etc.) | Rich (filter, map, reduce, collect, etc.) |
Parallel Execution | Not inherently parallel | Easily parallelizable using parallelStream() |
Infinite Data Support | Cannot handle infinite data | Can work with infinite streams (e.g., Stream.iterate() ) |
API introduced in | Java 1.2 | Java 8 |
Examples | ArrayList , HashSet , HashMap , LinkedList |
filter() , map() , collect() , reduce() |
Reusability | Collections can be reused after use | Streams cannot be reused once consumed |
Null Handling | Allows null elements (e.g., in lists) | May throw NullPointerException on some operations |
Mutability | Can be mutable or immutable | Stream pipeline is immutable |
import java.util.*; public class CollectionsCustomExample { public static void main(String[] args) { List<String> names = Arrays.asList("LotusJavaPrince", "Mahesh", "Manish", "Aarav", "Alok", "Amit"); List<String> filteredNames = new ArrayList<>(); for (String name : names) { if (name.startsWith("A")) { filteredNames.add(name.toUpperCase()); } } for (String name : filteredNames) { System.out.println(name); } } }
The above program using Java8 streams.
import java.util.*; import java.util.stream.*; public class StreamsCustomExample { public static void main(String[] args) { List<String> names = Arrays.asList("LotusJavaPrince", "Mahesh", "Manish", "Aarav", "Alok", "Amit"); names.stream() .filter(name -> name.startsWith("A")) .map(String::toUpperCase) .forEach(System.out::println); } }
While traditional iteration is straightforward and familiar, the Stream API offers a modern approach that simplifies complex data processing tasks, enhances code readability, and leverages parallelism. As a result, Streams are often preferred for their elegance and efficiency in handling collections.