使用java8新特性 使用stream获取最大值比parallelStream快

测试代码

/*
 * 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是专为执行并行任务而生的),


在普通电脑上使用并行的代价太高,或许在大型服务器上核数比较多,才能体现出并行的威力



  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值