The Java Streams API allows for functional-style operations on sequences of elements, such as collections. You can filter, map, and reduce elements in a declarative way.
import java.util.Arrays; import java.util.List; public class StreamExample { public static void main(String[] args) { Listnumbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Filter even numbers and print them numbers.stream() .filter(n -> n % 2 == 0) .forEach(System.out::println); } }
This example uses the stream()
method to create a stream from the list of numbers, filters out even numbers, and prints each one.
import java.util.Arrays; import java.util.List; public class StreamExample { public static void main(String[] args) { Listnumbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Square the numbers and sum them int sum = numbers.stream() .map(n -> n * n) .reduce(0, Integer::sum); System.out.println("Sum of squares: " + sum); } }
This example demonstrates how to use the map()
method to square the numbers and then use reduce()
to sum them.