测试代码
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.test.stream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
/**
*
* @author guona
*/
public class TestStream {
public static void main(String[] args) {
List<Integer> list = createList(100 * 100 * 100);
long time = System.currentTimeMillis();
testStreamMax(list);
System.out.println(System.currentTimeMillis() - time);
time = System.currentTimeMillis();
testParallelStreamMax(list);
System.out.println(System.currentTimeMillis() - time);
}
public static List<Integer> createList(int num) {
List<Integer> list = new ArrayList<>();
Random random = new Random(100*10);
while (num > 0) {
num--;
list.add(random.nextInt());
}
return list;
}
public static void testParallelStreamMax(List<Integer> list) {
int max = list.parallelStream().max(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
}).get();
System.out.println("testParallelStreamMax max"+max);
}
public static void testStreamMax(List<Integer> list) {
int max = list.stream().max(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
}).get();
System.out.println("testStreamMax max"+max);
}
}
测试结果
testStreamMax max2147480306
78
testParallelStreamMax max2147480306
390
看了一下源码,发现并行Stream使用到了ForkJoinTask( ForkJoinTask是专为执行并行任务而生的),
在普通电脑上使用并行的代价太高,或许在大型服务器上核数比较多,才能体现出并行的威力