Java 8 introduced Streams, a powerful abstraction that allows for processing sequences of elements in a declarative and functional manner. Streams facilitate various operations on collections of data, like filtering, mapping, and reducing, enabling more concise and expressive code.
Key Characteristics of Streams:
- Sequential and Parallel Execution: Streams can operate in either mode, allowing for efficient multi-core processing.
- Pipeline of Operations: Streams support creating a pipeline of operations. Intermediate operations like filter, map, and sorted build the pipeline, while terminal operations like forEach, collect, and reduce execute it.
- Internal Iteration: Streams handle iteration internally, abstracting away explicit loops and enabling better performance optimizations.
Creating Streams:
Streams can be created from various sources:
Collections
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
Code language: PHP (php)
Arrays:
String[] array = {"a", "b", "c"};
Stream<String> stream = Arrays.stream(array);
Code language: JavaScript (javascript)
Static Methods:
Stream<String> stream = Stream.of("a", "b", "c");
Code language: JavaScript (javascript)
Stream Operations:
Intermediate Operations: These return a new stream and are lazy, meaning they are not executed until a terminal operation is called.
- filter(Predicate<T> predicate): Filters elements based on a predicate.
- map(Function<T, R> mapper): Transforms elements using a function.
- sorted(): Sorts elements.
Terminal Operations: These trigger the processing of the stream and produce a result or side-effect.
- forEach(Consumer<T> action): Performs an action for each element.
- collect(Collector<T, A, R> collector): Collects elements into a collection.
- reduce(BinaryOperator<T> accumulator): Reduces elements to a single value.
Java 8 Streams offer a modern, functional approach to processing collections, making code more readable, concise, and potentially more efficient by leveraging parallel processing.Â