package com.logicbig.example.stream;
import java.util.IntSummaryStatistics;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class MapToIntExample {
public static void main(String... args) {
String[] s = {"one", "two", "three", "four"};
Stream<String> stringStream = Stream.of(s);
IntStream intStream = stringStream.mapToInt(e -> e.length());
IntSummaryStatistics stats = intStream.peek(System.out::println)
.summaryStatistics();
System.out.println(stats);
}
}
Output
3
3
5
4
IntSummaryStatistics{count=4, sum=15, min=3, average=3.750000, max=5}
This example also shows the wrong use of side effect.
package com.logicbig.example;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
/**
* Even though this is thread safe, but the result is non-deterministic
*/
public class SideEffectWrongUse2 {
public static void main (String[] args) {
List<Integer> lengths = Collections.synchronizedList(new ArrayList<>());
Stream.of("Banana", "Pear", "Apple")
.peek(SideEffectWrongUse2::longTask)//applying side effect
.parallel()
.mapToInt(s -> s.length())
.forEach(lengths::add);//collecting via side effect
// updating state
System.out.println(lengths);
}
private static void longTask (String s) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output
[4, 5, 6]
Original Post