Question: Java - Summing the Triples of the even integers from 2 through 10 - The example of fig. 17.7 summed the triples of the even
Java - Summing the Triples of the even integers from 2 through 10 - The example of fig. 17.7 summed the triples of the even integers from 2 through 10. We first used filter and map in the stream pipeline to demonstrate both in one stream pipeline. Reimplement fig. 17.7's stream pipeline using only map (similar to fig 17.4)
Fig 17.7
import java.util.stream.IntStream;
public class StreamFilterMapReduce { public static void main(String[] args) { // sum the triples of the even integers from 2 through 10 System.out.printf( "Sum of the triples of the even ints from 2 through 10 is: %d%n", IntStream.rangeClosed(1, 10) .filter( x -> { System.out.printf("%nfilter: %d%n", x); return x % 2 == 0; }) .map( x -> { System.out.println("map: " + x); return x * 3; }) .sum()); } }
Fig 17.4
import java.util.stream.IntStream;
public class StreamMapReduce { public static void main(String[] args) { // sum the even integers from 2 through 20 System.out.printf("Sum of the even ints from 2 through 20 is: %d%n", IntStream.rangeClosed(1, 10) // 1...10 .map((int x) -> {return x * 2;}) // multiply by 2 .sum()); // sum } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
