map |
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
DoubleStream map(DoubleUnaryOperator mapper)
IntStream map(IntUnaryOperator mapper)
LongStream map(LongUnaryOperator)
peek |
Stream<T> peek(Consumer<? super T> action)
DoubleStream peek(DoubleConsumer action)
IntStream peek(IntConsumer action)
LongStream peek(LongConsumer action)
The method peek is an intermediate operation, the most common use for peek is to exam the stream contents without consuming it.
OCPJP>cat ExtractDataDemo.java
import java.util.stream.*;
import java.util.Arrays;
import java.util.List;
public class ExtractDataDemo {
public static void main(String[] args) {
List<String> list = Arrays.asList("a", "bbb", "cc");
Stream<String> stream = list.stream();
stream.map(i -> new StringBuffer(i + i).append("ok"))
.peek(i -> System.out.println("Stream<T>.map.peek: " + i.length())).count();
DoubleStream doubleStream = list.stream().mapToDouble(String::length);
doubleStream.map(Math::asin).peek(d -> System.out.println("DoubleStream.map.peek: " + d)).findFirst();
IntStream intStream = list.stream().mapToInt(String::length);
intStream.map(i -> i + 10).peek(i -> System.out.println("IntStream.map.peek: " + i)).summaryStatistics();
LongStream longstream = list.stream().mapToLong(String::length);
longstream.peek(i -> System.out.println("LongStream.peek.map: " + i)).map(i -> i + 10L).allMatch(i -> i > 10);
}
}
OCPJP>
OCPJP>
OCPJP>
OCPJP>javac ExtractDataDemo.java
OCPJP>java ExtractDataDemo
Stream<T>.map.peek: 4
Stream<T>.map.peek: 8
Stream<T>.map.peek: 6
DoubleStream.map.peek: 1.5707963267948966
IntStream.map.peek: 11
IntStream.map.peek: 13
IntStream.map.peek: 12
LongStream.peek.map: 1
LongStream.peek.map: 3
LongStream.peek.map: 2
OCPJP>
notice the effect of findFirst on the DoubleStream's peek method -- Stream is lazy, when the JVM executes the stream, it optimizes all the operations as a whole -- since FindFirst only need one element, peek didn't bother to peek a single extra element.