學(xué)習(xí)札記-Java8系列-10-詳解Stream操作

學(xué)習(xí)札記-Java8系列-10-詳解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ì)

統(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ū)

分組和分區(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, "蘋果手機(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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市赋除,隨后出現(xiàn)的幾起案子阱缓,更是在濱河造成了極大的恐慌,老刑警劉巖举农,帶你破解...
    沈念sama閱讀 211,376評(píng)論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件荆针,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡颁糟,警方通過(guò)查閱死者的電腦和手機(jī)航背,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,126評(píng)論 2 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)棱貌,“玉大人玖媚,你說(shuō)我怎么就攤上這事』橥眩” “怎么了今魔?”我有些...
    開(kāi)封第一講書人閱讀 156,966評(píng)論 0 347
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)障贸。 經(jīng)常有香客問(wèn)我错森,道長(zhǎng),這世上最難降的妖魔是什么篮洁? 我笑而不...
    開(kāi)封第一講書人閱讀 56,432評(píng)論 1 283
  • 正文 為了忘掉前任涩维,我火速辦了婚禮,結(jié)果婚禮上嘀粱,老公的妹妹穿的比我還像新娘激挪。我一直安慰自己,他們只是感情好锋叨,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,519評(píng)論 6 385
  • 文/花漫 我一把揭開(kāi)白布垄分。 她就那樣靜靜地躺著,像睡著了一般娃磺。 火紅的嫁衣襯著肌膚如雪薄湿。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書人閱讀 49,792評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音豺瘤,去河邊找鬼吆倦。 笑死,一個(gè)胖子當(dāng)著我的面吹牛坐求,可吹牛的內(nèi)容都是我干的蚕泽。 我是一名探鬼主播,決...
    沈念sama閱讀 38,933評(píng)論 3 406
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼桥嗤,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼须妻!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起泛领,我...
    開(kāi)封第一講書人閱讀 37,701評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤荒吏,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后渊鞋,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體绰更,經(jīng)...
    沈念sama閱讀 44,143評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,488評(píng)論 2 327
  • 正文 我和宋清朗相戀三年锡宋,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了儡湾。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,626評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡员辩,死狀恐怖盒粮,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情奠滑,我是刑警寧澤丹皱,帶...
    沈念sama閱讀 34,292評(píng)論 4 329
  • 正文 年R本政府宣布,位于F島的核電站宋税,受9級(jí)特大地震影響摊崭,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜杰赛,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,896評(píng)論 3 313
  • 文/蒙蒙 一呢簸、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧乏屯,春花似錦根时、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 30,742評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至含友,卻和暖如春替裆,著一層夾襖步出監(jiān)牢的瞬間校辩,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 31,977評(píng)論 1 265
  • 我被黑心中介騙來(lái)泰國(guó)打工辆童, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留宜咒,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,324評(píng)論 2 360
  • 正文 我出身青樓把鉴,卻偏偏與公主長(zhǎng)得像故黑,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子纸镊,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,494評(píng)論 2 348

推薦閱讀更多精彩內(nèi)容