In Java, a Stream is a sequence of elements that can be processed in parallel or sequentially. Introduced in Java 8, Streams provide a functional approach to process collections, arrays, or I/O channels.
They allow operations like filtering, mapping, sorting, and collecting, making code more readable and expressive.
Streams are not data structures; they do not store data but convey elements from a source (like a collection). Key operations on Streams include:
1. Intermediate operations: Transform the data (e.g., filter(), map(), sorted()) and return a new stream.
2. Terminal operations: Produce a result or side effect (e.g., collect(), forEach(), reduce(), count()).
Example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.filter(n -> n > 2)
.mapToInt(Integer::intValue)
.sum();
System.out.println(sum); // Output: 12
Streams enable efficient data processing, especially when dealing with large datasets or parallel operations.