运行代码
package com.stream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* Created by lipei on 2017/8/26.
*
* 测试stream的效率
*
*/
public class StreamTest {
public static void main(String[] args) {
System.out.println("for循环开始时间:" + LocalDateTime.now());
long totalVal02 = 0;
for(int i = 1; i<= 100; i++){
totalVal02 += getNum(i);
}
System.out.println("totalNum = " + totalVal02);
System.out.println("for循环结束时间:" + LocalDateTime.now());
//串行
System.out.println("Stream 开始时间:" + LocalDateTime.now());
long totalVal01 = Stream.iterate(1, n->n+1).limit(100).collect(Collectors.summingLong(StreamTest::getNum));
System.out.println("totalNum = " + totalVal01);
System.out.println("Stream 结束时间:" + LocalDateTime.now());
//并行
System.out.println("parallel Stream 开始时间:" + LocalDateTime.now());
long totalVal03 = Stream.iterate(1, n->n+1).limit(100).parallel().collect(Collectors.summingLong(StreamTest::getNum));
System.out.println("totalNum = " + totalVal03);
System.out.println("parallel Stream 结束时间:" + LocalDateTime.now());
}
public static long getNum(int m){
Long totalNum = Long.valueOf(0);
for(long i = 1; i <= 100000000l; i++){
totalNum += m ;
}
return totalNum;
}
}
运行结果
for循环开始时间:2017-08-28T09:59:43.481
totalNum = 505000000000
for循环结束时间:2017-08-28T10:00:17.044
Stream 开始时间:2017-08-28T10:00:17.044
totalNum = 505000000000
Stream 结束时间:2017-08-28T10:00:50.738
parallel Stream 开始时间:2017-08-28T10:00:50.738
totalNum = 505000000000
parallel Stream 结束时间:2017-08-28T10:01:12.503
Process finished with exit code 0