Java9新特性:StreamAPI改进

Java8出现的API大大简化了集合操作:

        List<String> strings = List.of("abc", "bc", "efg", "gg", "abcd", "jkl");
        //集合中空字符串个数
        System.out.println(strings.parallelStream().filter(String::isEmpty).count());
        //去掉空字符串
        List<String> newStrings = strings.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
        //限制输出个数
        newStrings.stream().limit(3).forEach(System.out::println);
        System.out.println();
        //排序
        newStrings.stream().sorted().forEach(System.out::println);
        System.out.println();
        //集合元素合并成字符串
        System.out.println(newStrings.stream().collect(Collectors.joining(",")));
        List<Integer> ints = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        IntSummaryStatistics statistics = ints.stream().mapToInt((x) -> x).summaryStatistics();
        System.out.println("max:" + statistics.getMax());
        System.out.println("min:" + statistics.getMin());
        System.out.println("sum:" + statistics.getSum());
        System.out.println("average:" + statistics.getAverage());
        System.out.println("count:" + statistics.getCount());

结果如下:

0
abc
bc
efg

abc
abcd
bc
efg
gg
jkl

abc,bc,efg,gg,abcd,jkl
max:10
min:1
sum:55
average:5.5
count:10

到了Java9之后,增加了如下方法:

        List<String> strings = List.of("abc", "bc", "efg", "gg", "abcd", "jkl");
        //输出集合元素直到遇到不符合条件的字符串
        strings.stream().takeWhile(s -> !s.equals("gg")).forEach(System.out::println);
        System.out.println();
        //从不符合条件的字符串开始输出集合元素
        strings.stream().dropWhile(s -> !s.equals("gg")).forEach(System.out::println);
        //指定初始值创建顺序流,设置停止条件与每次迭代的操作
        IntStream.iterate(0, x -> x <= 10, x -> x + 2).forEach(System.out::println);

结果如下:

abc
bc
efg

gg
abcd
jkl
0
2
4
6
8
10


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值