Java8 Stream API

创建Stream的4种方式

    /**
     * 创建Stream
     */
    @Test
    public void test1() {
        //1. Collection 提供了两个方法  stream() 与 parallelStream()
        List<String> list = new ArrayList<>();
        Stream<String> stream = list.stream(); //获取一个顺序流
        Stream<String> parallelStream = list.parallelStream(); //获取一个并行流

        //2. 通过 Arrays 中的 stream() 获取一个数组流
        Integer[] nums = new Integer[10];
        Stream<Integer> stream1 = Arrays.stream(nums);

        //3. 通过 Stream 类中静态方法 of()
        Stream<Integer> stream2 = Stream.of(1, 2, 3, 4, 5, 6);

        //4. 创建无限流
        //迭代
        Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);
        //生成
        Stream<Double> stream4 = Stream.generate(Math::random).limit(2);
    }

过滤和截取

 /**
     * 过滤和截取
     */
    @Test
    public void test2() {
        Integer[] nums = new Integer[]{3, 1, 10, 5, 2, 6};
        Stream<Integer> stream = Arrays.stream(nums);
        stream.filter((x) -> x > 2).limit(2).forEach(System.out::println);
    }

映射

    /**
     * 映射
     * map  把每一个元素映射成一个新的元素
     * <p>
     * flatMap  把每一个流的值转换成一个新的流,然后把所有的新流连接成一个流
     */
    @Test
    public void test3() {
        String[] strs = new String[]{"aa", "bb"};
        Stream<String> stream = Arrays.stream(strs);
        stream.map(x -> x + "Mock").forEach(System.out::println);//{"aaMock", "bbMock"};

        Stream<Stream<Character>> streamStream = stream.map(x -> getCharacter(x));//[{aa},{bb}]
        streamStream.forEach(x -> x.forEach(System.out::println));

        Stream<Character> characterStream = stream.flatMap(x -> getCharacter(x));//{aabb}

    }

    private Stream<Character> getCharacter(String str) {
        List<Character> list = new ArrayList<>();
        for (Character ch : str.toCharArray()) {
            list.add(ch);
        }
        return list.stream();
    }

排序

    /**
     * 排序
     */
    @Test
    public void test4() {
        //List排序
        Arrays.asList("c", "a", "b").stream().sorted((x, y) -> x.compareTo(y)).forEach(System.out::println);

        //Map排序
        Map<String, String> map = new HashMap<>();
        map.put("c", "c");
        map.put("a", "a");
        map.put("b", "b");
        map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(x -> System.out.println(x.getKey()));
    }

查找与匹配

    /**
     * 查找与匹配
     * allMatch 所有匹配
     * anyMatch 任何匹配就可以
     * noneMatch 没有匹配
     * findFirst 找第一个
     * findAny 随便找一个
     * count 总个数
     * max 最大值
     * min 最小值
     */
    @Test
    public void test5() {
        Arrays.asList("c", "a", "b").stream().allMatch(x -> "a".equals(x));//false
        Optional<String> any = Arrays.asList("c", "a", "b").stream().findAny();
        Optional<String> max = Arrays.asList("c", "a", "b").stream().max((x, y) -> x.compareTo(y));
    }

收集

    /**
     * 收集
     * reduce
     * collect
     */
    @Test
    public void test6() {
        //使用reduce取得和
        Integer[] num = new Integer[]{4, 5, 2, 3};
        Integer sum = Arrays.asList(num).stream().reduce(0, (x, y) -> x + y);
        Integer sum2 = Arrays.asList(num).stream().reduce(0, Integer::sum);

        ArrayList<Integer> collect = Arrays.asList(new Integer[]{4, 5, 2, 3})
                .stream().map(x -> x + 1).collect(Collectors.toCollection(ArrayList::new));
        List<Integer> collect1 = Arrays.asList(new Integer[]{4, 5, 2, 3})
                .stream().map(x -> x + 1).collect(Collectors.toList());

        //求总数
        Long cout = Arrays.asList(new Integer[]{4, 5, 2, 3})
                .stream().collect(Collectors.counting());

        //求平均值
        Double avg = Arrays.asList(new Integer[]{4, 5, 2, 3})
                .stream().collect(Collectors.averagingInt(x -> x));

        //求最大值
        Optional<Integer> max = Arrays.asList(new Integer[]{4, 5, 2, 3}).stream()
                .collect(Collectors.maxBy((x, y) -> x.compareTo(y)));
        System.out.println(max.get());
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值