Java Reference
In-Depth Information
The following snippet of code uses the
peek()
method at three places to print the elements passing through the
stream pipeline:
int sum = Stream.of(1, 2, 3, 4, 5)
.peek(e -> System.out.println("Taking integer: " + e))
.filter(n -> n % 2 == 1)
.peek(e -> System.out.println("Filtered integer: " + e))
.map(n -> n * n)
.peek(e -> System.out.println("Mapped integer: " + e))
.reduce(0, Integer::sum);
System.out.println("Sum = " + sum);
Taking integer: 1
Filtered integer: 1
Mapped integer: 1
Taking integer: 2
Taking integer: 3
Filtered integer: 3
Mapped integer: 9
Taking integer: 4
Taking integer: 5
Filtered integer: 5
Mapped integer: 25
Sum = 35
Notice that the output shows the even numbers being taken from the data source, but not passing the filter
operation.
Applying the ForEach Operation
The forEach operation takes an action for each element of the stream. The action may be simply printing each element
of the stream on the standard output or increasing the income of every person in a stream by 10%. The
Stream<T>
interface contains two methods to perform the forEach operation:
•
void forEach(Consumer<? super T> action)
void forEachOrdered(Consumer<? super T> action)
IntStream
,
LongStream
, and
DoubleStream
also contain the same methods, except that their parameter type
is the specialized consumer types for primitives; for example, the parameter type for the
forEach()
method in the
IntStream
is
IntConsumer
.
Why do you have two methods to perform the forEach operation? Sometimes the order in which the action is
applied for the elements in a stream is important, and sometimes it is not. The
forEach()
method does not guarantee
the order in which the action for each element in the stream is applied. The
forEachOrdered()
method performs the
action in the encounter order of elements defined by the stream. Use the
forEachOrdered()
method for a parallel
stream only when necessary because it may slow down processing.
•