Cómo usar mapa, filtrar y reducir en Java
import java.util.stream.IntStream;
public class StreamOperations {
public static void main(String[] args) {
int[] values = {3, 10, 6, 1};
// Sum of values via reduce method
System.out.printf("Sum: %d%n",
IntStream.of(values)
.reduce(0, (x, y) -> x + y)); // Sum: 20
// Product via reduce
System.out.printf("Product: %d%n",
IntStream.of(values)
.reduce(1, (x, y) -> x*y)); // Product: 180
// Even values multiplied by 10
// and displayed in sorted order
// Printing: 60 100
IntStream.of(values)
.filter(value -> value % 2 == 0)
.map(value -> value * 10)
.sorted()
.forEach(value -> System.out.printf("%d ", value));
}
}
Wissam