Java8函數(shù)式編程-包教包會(huì)系列(十)

作者:曹偉,叩丁狼教育高級(jí)講師。原創(chuàng)文章,轉(zhuǎn)載請(qǐng)注明出處。

詳解Stream操作

操作步驟

使用Stream API操作數(shù)據(jù)可以分為以下幾個(gè)步驟:

1)創(chuàng)建流:
通過(guò)數(shù)據(jù)源(如:集合、數(shù)組)獲取流

2)處理流:(中的數(shù)據(jù))
對(duì)流中的數(shù)據(jù)進(jìn)行處理(處理是延遲執(zhí)行的)

3)收集流:(中的數(shù)據(jù))
通過(guò)調(diào)用收集方法,真正執(zhí)行處理操作,并產(chǎn)生結(jié)果

創(chuàng)建流

創(chuàng)建一個(gè)流非常簡(jiǎn)單,有以下幾種常用的方式:

1)Collection的默認(rèn)方法stream()和parallelStream()
2)Arrays.stream()
3)Stream.of()
4)Stream.iterate()//迭代無(wú)限流(1, n->n +1)
5)Stream.generate()//生成無(wú)限流(Math::random)

代碼實(shí)現(xiàn)

@Test
public void testCreateStream() throws Exception {
    // 1.Collection的默認(rèn)方法stream()和parallelStream()
    List<String> list = Arrays.asList("a", "b", "c");
    Stream<String> stream = list.stream();// 獲取順序流
    Stream<String> parallelStream = list.parallelStream();

    // 2.Arrays.stream()
    IntStream intStream = Arrays.stream(new int[] { 1, 2, 3 });
    Stream<Integer> IntegerStream = Arrays.stream(new Integer[] { 1, 2, 3 });

    // 3.Stream.of()
    Stream<Integer> IntegerStream2 = Stream.of(1, 2, 3, 4);
    IntStream intStream2 = IntStream.of(1, 2, 3);

    // 4.Stream.iterate()//迭代無(wú)限流
    // Stream.iterate(1, n->n +1).forEach(System.out::println);
    Stream.iterate(1, n -> n + 1).limit(100).forEach(System.out::println);

    // 5.Stream.generate()//生成無(wú)限流
    // Stream.generate(Math::random).forEach(System.out::println);
    Stream.generate(Math::random).limit(2).forEach(System.out::println);
}

處理流

篩選和切片

filter(Predicate<T> p):過(guò)濾(根據(jù)傳入的Lambda返回的ture/false 從流中過(guò)濾掉某些數(shù)據(jù)(篩選出某些數(shù)據(jù)))

distinct():去重(根據(jù)流中數(shù)據(jù)的 hashCode和 equals去除重復(fù)元素)
limit(long n):限定保留n個(gè)數(shù)據(jù)
skip(long n):跳過(guò)n個(gè)數(shù)據(jù)

圖解:


image.png

image.png

代碼實(shí)現(xiàn)

@Test
public void test1() throws Exception {
    Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().filter(i -> i % 2 == 0).forEach(System.out::println);
    System.out.println("================================================");
    Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);
    System.out.println("================================================");
    Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().distinct().limit(2).forEach(System.out::println);
    System.out.println("================================================");
    Arrays.asList(1, 2, 1, 3, 3, 2, 4).stream().distinct().skip(2).forEach(System.out::println);
}

映射

映射
map(Function<T, R> f):接收一個(gè)函數(shù)作為參數(shù),該函數(shù)會(huì)被應(yīng)用到流中的每個(gè)元素上,并將其映射成一個(gè)新的元素。
flatMap(Function<T, Stream<R>> mapper):接收一個(gè)函數(shù)作為參數(shù),將流中的每個(gè)值都換成另一個(gè)流,然后把所有流連接成一個(gè)流

圖解

image.png
image.png

代碼實(shí)現(xiàn)

@Test
public void test3() throws Exception {
    System.out.println("=======================map=========================");
    Stream<String> stream = Stream.of("i","love","java");
    stream.map(s -> s.toUpperCase()).forEach(System.out::println);
    System.out.println("=======================flatMap========================");
    Stream<List<String>> stream2 = Stream.of(Arrays.asList("H","E"), Arrays.asList("L", "L", "O"));
    stream2.flatMap(list -> list.stream()).forEach(System.out::println);
}

排序

排序

sorted():自然排序使用Comparable<T>的int compareTo(T o)方法
sorted(Comparator<T> com):定制排序使用Comparator的int compare(T o1, T o2)方法

代碼實(shí)現(xiàn)

@Test
public void test4() throws Exception {
    System.out.println("====================自然排序============================");
    Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().sorted().forEach(System.out::println);
    System.out.println("====================定制排序============================");
    Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().sorted((x,y) -> y.compareTo(x)).forEach(System.out::println);
}

收集流

查找匹配

allMatch:檢查是否匹配所有元素
anyMatch:檢查是否至少匹配一個(gè)元素
noneMatch:檢查是否沒(méi)有匹配的元素
findFirst:返回第一個(gè)元素(返回值為Optional<T>)
findAny:返回當(dāng)前流中的任意元素(一般用于并行流)

備注:

Optional<T>是Java8新加入的一個(gè)容器,這個(gè)容器只存1個(gè)或0個(gè)元素,它用于防止出現(xiàn)NullpointException,它提供如下方法:

?isPresent()

判斷容器中是否有值。

?ifPresent(Consume lambda)

容器若不為空則執(zhí)行括號(hào)中的Lambda表達(dá)式。

?T get()

獲取容器中的元素,若容器為空則拋出NoSuchElement異常。

?T orElse(T other)

獲取容器中的元素,若容器為空則返回括號(hào)中的默認(rèn)值。

代碼實(shí)現(xiàn)

@Test
public void test5() throws Exception {
    System.out.println("======================檢查是否匹配所有==========================");
    boolean allMatch = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().allMatch(x-> x>0);
    System.out.println(allMatch);
    System.out.println("======================檢查是否至少匹配一個(gè)元素====================");
    boolean anyMatch = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().anyMatch(x -> x>7);
    System.out.println(anyMatch);
    System.out.println("======================檢查是否沒(méi)有匹配的元素======================");
    boolean noneMatch = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().noneMatch(x -> x >10);
    System.out.println(noneMatch);
    System.out.println("======================返回第一個(gè)元素==========================");
    Optional<Integer> first = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().findFirst();
    System.out.println(first.get()); 
    System.out.println("======================返回當(dāng)前流中的任意元素=======================");
    Optional<Integer> any = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().findAny();
    System.out.println(any.get());
}

統(tǒng)計(jì)

count():返回流中元素的總個(gè)數(shù)
max(Comparator<T>):返回流中最大值
min(Comparator<T>):返回流中最小值

代碼實(shí)現(xiàn)

@Test
public void test6() throws Exception {
    long count = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().count();
    System.out.println(count);
    Optional<Integer> max = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().max((x,y) -> x.compareTo(y));
    System.out.println(max.get());
    Optional<Integer> min = Arrays.asList(3, 2, 1, 4, 5, 8, 6).stream().min((x,y) -> x.compareTo(y));
    System.out.println(min.get());
}

歸約

reduce(T identity, BinaryOperator) / reduce(BinaryOperator) :將流中元素挨個(gè)結(jié)合起來(lái),得到一個(gè)值。

圖解

image.png

代碼實(shí)現(xiàn)

@Test
public void test7() throws Exception {
    System.out.println("=====reduce:將流中元素反復(fù)結(jié)合起來(lái),得到一個(gè)值==========");
    Stream<Integer> stream = Stream.iterate(1, x -> x+1).limit(100);
    //stream.forEach(System.out::println);
    Integer sum = stream.reduce(0,(x,y)-> x+y);
    System.out.println(sum);
}

匯總

reduce擅長(zhǎng)的是生成一個(gè)值,如果想要從Stream生成一個(gè)集合或者M(jìn)ap等復(fù)雜的對(duì)象該怎么辦呢?終極武器collect()橫空出世!

collect(Collector<T, A, R>):將流轉(zhuǎn)換為其他形式。

需求:

collect:將流轉(zhuǎn)換為其他形式:list
collect:將流轉(zhuǎn)換為其他形式:set
collect:將流轉(zhuǎn)換為其他形式:TreeSet
collect:將流轉(zhuǎn)換為其他形式:map
collect:將流轉(zhuǎn)換為其他形式:sum
collect:將流轉(zhuǎn)換為其他形式:avg
collect:將流轉(zhuǎn)換為其他形式:max
collect:將流轉(zhuǎn)換為其他形式:min

代碼實(shí)現(xiàn)

@Test
public void test8() throws Exception {
    System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:list");
    List<Integer> list = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.toList());
    System.out.println(list);
    System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:set");
    Set<Integer> set = Arrays.asList(1, 1, 2, 2, 3, 3, 3).stream().collect(Collectors.toSet());
    System.out.println(set);
    System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:TreeSet");
    TreeSet<Integer> treeSet = Arrays.asList(1, 1, 2, 2, 3, 3, 3).stream().collect(Collectors.toCollection(TreeSet::new));
    System.out.println(treeSet);
    System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:map");
    Map<Integer, Integer> map = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.toMap(Integer::intValue, Integer::intValue));
    System.out.println(map);
    System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:sum");
    Integer sum = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.summingInt(Integer::intValue));
    System.out.println(sum);
    System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:avg");
    Double avg = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.averagingInt(Integer::intValue));
    System.out.println(avg);
    System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:max");
    Optional<Integer> max = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.maxBy(Integer::compareTo));
    System.out.println(max.get());
    System.out.println("=====collect:將流轉(zhuǎn)換為其他形式:min");
    Optional<Integer> min = Stream.iterate(1, x -> x+1).limit(100).collect(Collectors.minBy((x,y) -> x-y));
    System.out.println(min.get());
}

分組和分區(qū)

Collectors.groupingBy()對(duì)元素做group操作。
Collectors.partitioningBy()對(duì)元素進(jìn)行二分區(qū)操作。

圖解

image.png
image.png

準(zhǔn)備工作

private List<Product> products = new ArrayList<>();

@Before
public void init() {
    products.add(new Product(1L, "蘋(píng)果手機(jī)", 8888.88,"手機(jī)"));//注意:要給Product類加一個(gè)分類名稱dirName字段
    products.add(new Product(2L, "華為手機(jī)", 6666.66,"手機(jī)"));
    products.add(new Product(3L, "聯(lián)想筆記本", 7777.77,"電腦"));
    products.add(new Product(4L, "機(jī)械鍵盤", 999.99,"鍵盤"));
    products.add(new Product(5L, "雷蛇鼠標(biāo)", 222.22,"鼠標(biāo)"));
}

需求

根據(jù)商品分類名稱進(jìn)行分組
根據(jù)商品價(jià)格范圍多級(jí)分組
根據(jù)商品價(jià)格是否大于1000進(jìn)行分區(qū)

代碼實(shí)現(xiàn)

@Test
public void test9() throws Exception {
    System.out.println("=======根據(jù)商品分類名稱進(jìn)行分組==========================");
    Map<String, List<Product>> map = products.stream().collect(Collectors.groupingBy(Product::getDirName));
    System.out.println(map);
    System.out.println("=======根據(jù)商品價(jià)格范圍多級(jí)分組==========================");
    Map<Double, Map<String, List<Product>>> map2 = products.stream().collect(Collectors.groupingBy(
            Product::getPrice, Collectors.groupingBy((p) -> {
                if (p.getPrice() > 1000) {
                    return "高級(jí)貨";
                    } else {
                        return "便宜貨";
                        }
                })));
    System.out.println(map2);

}
@Test
public void test10() throws Exception {
    System.out.println("========根據(jù)商品價(jià)格是否大于1000進(jìn)行分區(qū)========================");
    Map<Boolean, List<Product>> map = products.stream().collect(Collectors.partitioningBy(p -> p.getPrice() > 1000));
    System.out.println(map);
}

總結(jié)

Streamvs Collection

雖然大部分情況下Stream是容器調(diào)用Collection.stream()方法得到的,但Stream和Collection有以下不同:

●無(wú)存儲(chǔ)。Stream不是一種數(shù)據(jù)結(jié)構(gòu),它只是某種數(shù)據(jù)源的一個(gè)視圖,數(shù)據(jù)源可以是一個(gè)數(shù)組,集合等。
●不修改。對(duì)Stream的任何修改都不會(huì)修改背后的數(shù)據(jù)源,比如過(guò)濾操作并不會(huì)刪除被過(guò)濾的元素,而是產(chǎn)生一個(gè)新Stream。
●惰式執(zhí)行。Stream上的操作并不會(huì)立即執(zhí)行,只有等到用戶真正需要結(jié)果的時(shí)候才會(huì)執(zhí)行。
●可消費(fèi)性。Stream只能被“消費(fèi)”一次,一旦遍歷過(guò)就會(huì)失效,就像容器的迭代器那樣,想要再次遍歷必須重新生成。

Stream分類

●中間操作(intermediate operations)
返回值為Stream的大都是中間操作,中間操作支持鏈?zhǔn)秸{(diào)用,并且會(huì)惰式執(zhí)行

●終端操作(結(jié)束操作)(terminal operations)
返回值不為Stream 的為終端操作(立即求值),終端操作不支持鏈?zhǔn)秸{(diào)用,會(huì)觸發(fā)實(shí)際計(jì)算

image.png
WechatIMG7.jpeg
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • Jav8中,在核心類庫(kù)中引入了新的概念,流(Stream)。流使得程序媛們得以站在更高的抽象層次上對(duì)集合進(jìn)行操作。...
    仁昌居士閱讀 4,105評(píng)論 0 6
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,688評(píng)論 19 139
  • Java8 in action 沒(méi)有共享的可變數(shù)據(jù),將方法和函數(shù)即代碼傳遞給其他方法的能力就是我們平常所說(shuō)的函數(shù)式...
    鐵牛很鐵閱讀 1,383評(píng)論 1 2
  • “21世紀(jì),我們先是學(xué)會(huì)了開(kāi)車,然后是學(xué)會(huì)了show自己,再然后是學(xué)會(huì)了尊敬網(wǎng)絡(luò),而嘴角主義者則以為,凡事凡...
    泡芙兮閱讀 221評(píng)論 0 1
  • 今天非常有幸在長(zhǎng)沙參加了貓叔的干貨分享會(huì)。 貓叔的分享分兩個(gè)部分,在第一部分貓叔梳理了比特幣和區(qū)塊鏈行業(yè)的發(fā)展...
    大宏520閱讀 301評(píng)論 0 2

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