Streams API
A Stream in Java is a sequence of objects that supports various methods which can be pipelined to produce the desired result. It allows you to process data declaratively.
How Stream Works
A Stream pipeline consists of three parts:
- Source: Collections, Arrays, or I/O channels.
- Intermediate Operations: Transform the stream (e.g.,
filter,map,sorted). These are lazy! - Terminal Operation: Produces a result (e.g.,
forEach,collect,count).
1. Filter
Selects elements based on a condition (Predicate).
list.stream().filter(s -> s.startsWith("A"))
2. Map
Transforms each element (Function).
list.stream().map(s -> s.toUpperCase())
3. Collect
Gathers the result into a Collection.
.collect(Collectors.toList())
Full Example
Output
Click Run to execute your code
Summary
- Streams make code readable and concise.
- They do not store data; they process it.
- Intermediate operations are lazy (nothing happens until a terminal op is called).
Enjoying these tutorials?