Streams
Stream API
Stream API Overview
- Introduced in Java 8, the Stream API provides a functional programming approach to process collections of data declaratively.
- Key Features:
- Lazy Evaluation: Operations are executed only when a terminal operation is invoked.
- Parallel Processing: Streams can process data concurrently.
- Immutability: Streams do not modify the source data.
- Non-Reusability: Streams cannot be reused after a terminal operation.
- Intermediate:
filter(),map(),sorted(). They return a new stream and are lazy. - Terminal:
forEach(),collect(),reduce(). Produce a result or side effect and consume the stream.
Common Stream Functions
Stream Functions
-
-
filter(Predicate): Filters elements.
Intermediate Operations:
-
map(Function): Transforms elements. -
sorted(): Sorts elements. -
distinct(): Removes duplicates.
-
-
Terminal Operations:
-
forEach(Consumer): Performs an action for each element. -
collect(Collector): Collects elements into a collection. -
reduce(BinaryOperator): Reduces elements to a single value. -
count(): Counts elements.
-
Parallel Streams
Parallel Streams
- Parallel streams divide data into chunks for concurrent processing.
- Use
parallelStream()orstream().parallel().
- Avoid
sorted()with parallel streams due to unpredictable results.
List<Integer> numbers = Arrays.asList(5, 3, 1, 4, 2);
// Sequential stream with sorted
List<Integer> sortedNumbers = numbers.stream()
.sorted()
.collect(Collectors.toList());
System.out.println(sortedNumbers); // Outputs: [1, 2, 3, 4, 5]
// Avoid using sorted with parallel streams
List<Integer> parallelSortedNumbers = numbers.parallelStream()
.sorted()
.collect(Collectors.toList());
System.out.println(parallelSortedNumbers); // May produce unpredictable results
forEach Method
forEach Method
- A terminal operation used for side effects like printing or logging.
- Avoid modifying the data source within
forEach.