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() 從一堆對(duì)象中創(chuàng)建 Stream 流。

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

取代 for 循環(huán)

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 流的處理是隨著鏈條垂直移動(dòng)的。比如說(shuō),當(dāng) Stream 開始處理第一個(gè)元素時(shí),它實(shí)際上會(huì)執(zhí)行完filter 后,再執(zhí)行 forEach,接著才會(huì)處理第二個(gè)元素。

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 移動(dòng)到鏈頭的最開始,就可以大大減少實(shí)際的執(zhí)行次數(shù)。這種小技巧對(duì)于流中存在大量元素來(lái)說(shuō),是非常有用的。

排序,sorted 是水平執(zhí)行的。

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

復(fù)用流的方法

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)) 全面的統(tǒng)計(jì)信息,摘要收集器計(jì)算出總數(shù)量,總和,最小值,平均值和最大值。

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}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容