木头人的gravatar头像
木头人 2018-08-08 10:08:04

java8并行流处理实例

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;

/**
 * @Auther: jack
 * @Date: 2018/7/24 11:05
 * @Description: jdk8 并行流处理
 */
public class StreamParallel {
    public static void main(String[] args) {
        //rangeClosed包含末尾数据
        long sum=LongStream.rangeClosed(1,10000000L).parallel().reduce(0,Long::sum);
        System.out.println(sum);

        //range不包含末尾节点
        sum=LongStream.range(1,10000000L).parallel().reduce(0,Long::sum);
        System.out.println(sum);

        //求和reduce()
        System.out.println(Stream.of(1,2,3,4).reduce((sum2,item)->{
            return sum2+item;
        }).get());
        System.out.println(Stream.of(1,2,3,4).reduce(Integer::sum).get());

        //求最大值reduce()
        System.out.println(Stream.of(1,2,3,4).reduce(100,(a,b)->Math.max(a, b)));
        System.out.println(Stream.of(1,2,3,4).reduce(Integer::max).get());

        //去重distinct()
        System.out.println(Arrays.asList("a", "b", "c", "d", "a", "b", "c")
                .stream()
                .distinct()
                .collect(Collectors.toList())
        );

        //统计分组
        System.out.println(Arrays.asList("apple", "apple", "banana",
                "apple", "orange", "banana", "papaya")
                .stream()
                .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
        );

        //统计排序
        Map<String,Long> sortMap=new LinkedHashMap<>();
        Arrays.asList("apple", "apple", "banana", "apple", "orange", "banana", "papaya")
                .stream()
                .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
                .entrySet()
                .stream()
                .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
                .forEachOrdered(e->sortMap.put(e.getKey(),e.getValue()));
        System.out.println(sortMap);
    }
}

运行结果:java8并行流处理实例


最代码官方编辑于Aug 8, 2018 2:50:25 PM

打赏

已有1人打赏

最代码官方的gravatar头像

最代码最近下载分享源代码列表最近下载
最代码最近浏览分享源代码列表最近浏览
浪里格朗  LV4 2023年1月31日
jxdgogogo 2020年11月9日
暂无贡献等级
sularman  LV2 2020年10月23日
linjh123  LV1 2020年7月2日
zdm_ziming  LV1 2020年6月19日
a1677596408  LV23 2020年6月16日
wdeshijie  LV11 2020年6月12日
taocui  LV2 2020年5月19日
dg_wangjianlin  LV2 2020年3月4日
wkc  LV21 2020年2月3日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友