木头人的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头像

顶部客服微信二维码底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友