Stream API
- The Stream API introduced in Java 8.
- Powerful feature for processing collections of data in a functional and declarative way.
- It does not store data; it can be Stateless or Stateful.
Stream Characteristics
- Lazy Evaluation: Operations on streams are not performed until a terminal operation is invoked.
- Immutable: Streams do not modify the original data source; they work on a copy or a pipeline of transformations.
- Single-use: A stream can only be consumed once; it cannot be reused.
Stream vs Collection Comparison
Aspect | Stream | Collection |
---|---|---|
Storage | Does not store elements. | Stores elements. |
Iteration | Internal (abstracted). | External (manual loops). |
Operation Style | Functional and declarative. | Imperative. |
Laziness | Lazy and executed on demand. | Eager (operations are performed immediately). |
Reusability | Not reusable after terminal operation. | Can be reused multiple times. |
How Stream Works
Stream Operations
- Source: Streams are created from a data source (e.g.,
List
,Set
,Array
,Map
, orI/O channel
).
List names = Arrays.asList("Alice", "Bob", "Charlie");
Stream stream = names.stream();
- Intermediate Operations: These operations transform a stream into another stream. They are lazy and only prepare the pipeline for execution. Examples:
filter(Predicate)
map(Function)
flatMap()
distinct()
sorted()
skip()
- Terminal Operations: These operations trigger the processing pipeline and produce a result or side effect. Examples:
collect()
forEach()
reduce()
count()
toArray()
findFirst()
findAny()
allMatch()
Stream Creation
From Collections: Created by calling the stream()
method from the Collection interface.
List list = Arrays.asList(1, 2, 3);
Stream stream = list.stream();
From Arrays: Created using Arrays.stream()
.
int[] arr = {1, 2, 3};
IntStream intStream = Arrays.stream(arr);
From Files: Created using Files.lines(Paths.get(filePath))
.
Stream lines = Files.lines(Paths.get("file.txt"));
0 Comments