Using Stream for Functional-style Operations on Collections in Java

Introduced with Java 8, the Stream API offers a functional approach to processing sequences of elements, commonly from collections such as lists or sets. This API promotes a cleaner and more efficient way of handling data manipulations, offering a more streamlined syntax than classic loops. Java streams can operate either sequentially or in parallel. They offer operations like filter, map, and reduce, which can be seamlessly combined to create a processing pipeline. In this Java Stream Example, we showed the capabilities of Java streams when working with data. Click Execute to run the Java Stream Example online and see the result.
Using Stream for Functional-style Operations on Collections in Java Execute
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        List<Integer> squaredEvens = numbers.stream()
                                            .filter(n -> n % 2 == 0)
                                            .map(n -> n * n)
                                            .collect(Collectors.toList());

        System.out.println(squaredEvens);
    }
}
Updated: Viewed: 38 times