2019-05-16

List<String> myList = Arrays.asList("a1", "a2", "a3", "b1", "b2", "c1", "c2");
myList.stream()
        .filter(s -> s.startsWith("c"))
        .map(String::toUpperCase)
        .sorted()
        .forEach(System.out::println);

Stream.of() 从一堆对象中创建 Stream 流。

Stream.of("a1", "a2", "a3", "b1", "b2", "c1", "c2")
        .findFirst()
        .ifPresent(System.out::println);

取代 for 循环

IntStream.range(1, 4)
        .forEach(System.out::println);

sum() / average()

Arrays.stream(new int[]{1, 2, 3})
        .map(n -> 2 * n + 1)
        .average()
        .ifPresent(System.out::println);

mapToInt() / mapToLong() / mapToDouble

Stream.of("a1", "a2", "a3")
        .map(s -> s.substring(1))
        .mapToInt(Integer::parseInt)
        .max()
        .ifPresent(System.out::println);

mapToObj()

IntStream.range(1, 4)
        .mapToObj(i -> "a" + i)
        .forEach(System.out::println);

组合示例

Stream.of(1.0, 2.0, 3.0)
        .mapToInt(Double::intValue)
        .mapToObj(i -> "a" + i)
        .forEach(System.out::println);

Stream 流的处理是随着链条垂直移动的。比如说,当 Stream 开始处理第一个元素时,它实际上会执行完filter 后,再执行 forEach,接着才会处理第二个元素。

Stream.of("d2", "a2", "b1", "b3", "c")
        .map(s -> {
            System.out.println("map: " + s);
            return s.toUpperCase();
        })
        .anyMatch(s -> {
            System.out.println("anyMatch: " + s);
            return s.startsWith("A");
        });

map: d2
anyMatch: D2
map: a2
anyMatch: A2

所以我们改变中间操作的顺序,将 filter 移动到链头的最开始,就可以大大减少实际的执行次数。这种小技巧对于流中存在大量元素来说,是非常有用的。

排序,sorted 是水平执行的。

Stream.of("d2", "a2", "b1", "b3", "c")
        .sorted(String::compareTo)
        .forEach(System.out::println);

复用流的方法

Supplier<Stream<String>> streamSupplier = () -> Stream.of("d2", "a2", "b1", "b3", "c")
                .filter(s -> s.startsWith("a"));
        streamSupplier.get().anyMatch(s -> true);
        streamSupplier.get().noneMatch(s -> true);

.collect(Collectors.toList())
.collect(Collectors.toSet())
.collect(Collectors.groupingBy(p -> p.age))
.collect(Collectors.averagingInt(p -> p.age))
.collect(Collectors.summarizingInt(p -> p.age)) 全面的统计信息,摘要收集器计算出总数量,总和,最小值,平均值和最大值。

IntSummaryStatistics collect = persons.stream()
        .collect(Collectors.summarizingInt(Person::getAge));
System.out.println(collect);

IntSummaryStatistics{count=4, sum=76, min=12, average=19.000000, max=23}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 代表们来自: 安徽六安 福建泉州 广东佛山 广西桂林 讲题:压力与情绪管理
    李克富阅读 431评论 0赞 6
  • 今天看了一部电影 陪安东尼度过漫长的岁月, 也许是我太年轻。 或者是我逻辑不清晰。 如果说陪伴是最长情的告白的话。...
    冬生弟弟阅读 955评论 0赞 0
  • 【月检视】2018.9.3 石家庄 在家 【2018年度目标及检视完成情况】 【月度成果&温馨时刻】 一、健康: ...
    牛晓倩阅读 236评论 0赞 0

友情链接更多精彩内容