In Java 8 and later, the java.util.stream
package provides the Stream
interface, which represents a sequence of elements that can be processed sequentially or in parallel.
A Stream
can be created from a variety of sources, such as a Collection
, an array, a generator function, or an I/O channel.
Once a Stream
is created, it can be transformed and processed using a variety of intermediate and terminal operations.
Intermediate operations are operations that return a new Stream
, such as filter
, map
, or sorted
, and allow you to transform the elements of the Stream
in various ways.
Terminal operations are operations that return a result or perform an action on the elements of the Stream
, such as collect
, count
, or forEach
, and allow you to consume the elements of the Stream
.
Here is an example of how you can use the Stream
interface to filter a List
of integers and calculate the sum of the even numbers:
import java.util.List; import java.util.Arrays; public class MyClass { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); int sum = numbers.stream() .filter(n -> n % 2 == 0) // keep only even numbers .mapToInt(n -> n) // convert to IntStream .sum(); // calculate the sum System.out.println(sum); // Outputs 30 } }
In this example, the numbers
List
contains the integers from 1 to 10.
The filter
intermediate operation keeps only the even numbers, the mapToInt
intermediate operation converts the Stream
of integers to an IntStream
, and the sum
terminal operation calculates the sum of the even numbers.
The result of the stream processing is printed to the console.