映射归约
# 并行流
并行流将任务分配给多个线程完成;
# parallel
parallel方法将串行流转换为并行流;
public class Parallel_test {
public static void main(String[] args) {
Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9);
Integer sum = stream.parallel().peek(new Consumer<Integer>(){
@Override
public void accept(Integer num) {
System.out.println(num+Thread.currentThread().getName());
}
}).filter(num->num>5)
.reduce((result,ele)->result+ele)
.get();
System.out.println(sum);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
输出:
6main 3ForkJoinPool.commonPool-worker-9 5main 4ForkJoinPool.commonPool-worker-9 1main 7ForkJoinPool.commonPool-worker-4 9ForkJoinPool.commonPool-worker-13 8ForkJoinPool.commonPool-worker-2 2ForkJoinPool.commonPool-worker-11 30
# parallelStream
获取并行流对象;
List<Author> authors = getAuthors();
authors.parallelStream()
.map(author -> author.getAge())
.map(age -> age + 10)
.filter(age->age>18)
.map(age->age+2)
.forEach(System.out::println);
1
2
3
4
5
6
7
2
3
4
5
6
7