在线不卡日本ⅴ一区v二区_精品一区二区中文字幕_天堂v在线视频_亚洲五月天婷婷中文网站

  • <menu id="lky3g"></menu>
  • <style id="lky3g"></style>
    <pre id="lky3g"><tt id="lky3g"></tt></pre>

    「java8」阿里架構(gòu)師:Stream對集合的處理方式你全都知道了嗎?

    一、概述

    Stream 是 Java8 中處理集合的關(guān)鍵抽象概念,它可以指定你希望對集合進(jìn)行的操作,可以執(zhí)行非常復(fù)雜的查找、過濾和映射數(shù)據(jù)等操作。使用Stream API 對集合數(shù)據(jù)進(jìn)行操作,就類似于使用 SQL 執(zhí)行的數(shù)據(jù)庫查詢。也可以使用 Stream API來并行執(zhí)行操作。簡而言之,Stream API 提供了一種高效且易于使用的處理數(shù)據(jù)的方式。

    特點(diǎn):

    • 元素是特定類型的對象,形成一個隊(duì)列。 Java中的Stream并不會存儲元素,而是按需計(jì)算。
    • 數(shù)據(jù)源 流的來源。 可以是集合,數(shù)組,I/O channel, 產(chǎn)生器generator 等。
    • 聚合操作 類似SQL語句一樣的操作, 比如filter, map, reduce, find, match, sorted等。
    • Pipelining: 中間操作都會返回流對象本身。 這樣多個操作可以串聯(lián)成一個管道, 如同流式風(fēng)格(fluent style)。 這樣做可以對操作進(jìn)行優(yōu)化, 比如延遲執(zhí)行(laziness)和短路( short-circuiting)。
    • 內(nèi)部迭代: 以前對集合遍歷都是通過Iterator或者For-Each的方式, 顯式的在集合外部進(jìn)行迭代, 這叫做外部迭代。 Stream提供了內(nèi)部迭代的方式, 通過訪問者模式(Visitor)實(shí)現(xiàn)。

    二、Stream的創(chuàng)建

    Stream可以通過集合數(shù)組創(chuàng)建。

    1、通過 java.util.Collection.stream() 方法用集合創(chuàng)建流

    List list = Arrays.asList(1, 2, 3);// 創(chuàng)建一個順序流Stream stream = list.stream();// 創(chuàng)建一個并行流Stream parallelStream = list.parallelStream();

    2、使用java.util.Arrays.stream(T[] array)方法用數(shù)組創(chuàng)建流

    int[] array={1,3,5,6,8};IntStream stream = Arrays.stream(array);

    3、使用Stream的靜態(tài)方法:of()、iterate()、generate()(我不是很常用)

    Stream stream = Stream.of(1, 2, 3);// of內(nèi)部的方法,等同于使用數(shù)組創(chuàng)建流@SafeVarargs@SuppressWarnings(“varargs”) // Creating a stream from an array is safepublic static Stream of(T… values) {return Arrays.stream(values);}Stream stream2 = Stream.iterate(0, (x) -> x + 3).limit(4);stream2.forEach(System.out::print);System.out.println();Stream stream3 = Stream.generate(Math::random).limit(3);stream3.forEach(System.out::println);

    輸出結(jié)果:

    03690.49189549200548930.82466382643695550.17880449237798712

    將對象集合轉(zhuǎn)成對象中某個屬性的集合

    List list = new ArrayList();List ids = list.stream().map(ReviewerRest::getId).collect(Collectors.toList());復(fù)制代碼

    將某個屬性的集合轉(zhuǎn)成對象集合

    List ids = new ArrayList();List list = ids.stream().map(id -> {ReviewerRest rest = new ReviewerRest();rest.setRest(1);rest.setDate(LocalDate.now());rest.setReviewerId(1000L);return rest;}).collect(Collectors.toList());復(fù)制代碼

    判斷集合中是否有一個對象包含某個屬性

    boolean exist = list.stream().anyMatch(rest -> rest.getReviewerId().equals(1000L));//…… allMatch 和 anyMatch 類似復(fù)制代碼

    對集合中某個對象的屬性求和

    BigDecimal reduce = list.stream().map(ReviewerRest::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);復(fù)制代碼

    集合轉(zhuǎn) Map (普通)

    Map map = list.stream().collect(Collectors.toMap(ReviewerRest::getId, x -> x));復(fù)制代碼

    集合轉(zhuǎn) Map (key 存在重復(fù))

    當(dāng)集合中 id 會存在重復(fù)時,上面那種方式會報(bào)錯,此時需要指定重復(fù)時選用哪一個 value

    Map map = list.stream().collect(Collectors.toMap(ReviewerRest::getId, x -> x, (before, after) -> after));復(fù)制代碼

    集合轉(zhuǎn) Map (value 存在 null 值)

    當(dāng) value 存在 null 值時上面那種方式會報(bào)錯,此時需要換一種寫法

    Map map = list.stream().collect(HashMap::new, (mapItem, item) -> mapItem.put(item.getId(), item.getDate()), HashMap::putAll);復(fù)制代碼

    集合分組 轉(zhuǎn) Map

    Map map = list.stream().collect(Collectors.groupingBy(ReviewerRest::getId));復(fù)制代碼

    集合分區(qū) 轉(zhuǎn) Map

    Map map = list.stream().collect(Collectors.partitioningBy(r -> r.getRest() == 1));復(fù)制代碼

    集合分組個數(shù)統(tǒng)計(jì)

    Map map = list.stream().collect(Collectors.groupingBy(ReviewerRest::getId,Collectors.counting()));復(fù)制代碼

    集合分組轉(zhuǎn)某個屬性集合

    Map map = list.stream().collect(Collectors.groupingBy(ReviewerRest::getId,Collectors.mapping(ReviewerRest::getRest,Collectors.toList())));復(fù)制代碼

    集合分組聚合查詢最大元素

    Map map = list.stream().collect(Collectors.groupingBy(ReviewerRest::getReviewerId, Collectors.maxBy(Comparator.comparing(ReviewerRest::getDate))));復(fù)制代碼

    集合分組聚合求和

    //目前只支持 int、double、longMap map = list.stream().collect(Collectors.groupingBy(ReviewerRest::getReviewerId, Collectors.summingLong(

    java8采用stream對集合的常用操作

    User :{id,name,age}

    1.對象集合的分組(有兩種形式)示例:List userList,根據(jù)id分組,可以分組成為兩種格式的map(1)Map

    Map map = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

    (2)Map

    Map = userList.stream().collect(Collectors.groupingBy(User::getId));

    2.去重操作對List 實(shí)現(xiàn)去重,distinct關(guān)鍵字

    示例:userList= userList.stream().distinct().collect(Collectors.toList());

    3.stream的map主要用于得到特定的結(jié)構(gòu)例如:List userList,我向得到User Id的集合

    List idList = userList.stream.map(User::getId).collect(Collectors.toList());

    4.stream的filter主要用于數(shù)據(jù)的篩選。例1:一個條件的篩選,刪選id>5的User

    List userList = userList.stream.filter(i->i.getId()>5).collect(Collectors.toList());

    例2:兩個條件的刪選用&&連接就行,刪選id>5年紀(jì)>10的User

    List userList = userList.stream.filter(i->i.getId()>5&&i.getAge()>10).collect(Collectors.toList());

    5.用來作循環(huán)

    userList.stream().forEach(user -> System.out.println(“姓名:” + user.getName()));

    當(dāng)然也可以加個limit限制數(shù)量

    userList.stream().limit(2).forEach(user -> System.out.println(“姓名:” + user.getName()));

    6.最大值最小值

    int maxAge = userList.stream().mapToInt(User::getAge).max().getAsInt(); int minAge = userList.stream().mapToInt(User::getAge).min().getAsInt();

    封裝的Stream使用類,可以直接拿走使用:

    public class StreamUtils {/** * 集合為空,創(chuàng)建空的Stream流;否則創(chuàng)建集合的Stream流 * 避免出現(xiàn)空指針 * * @param collection 集合 * @param集合元素的泛型 * @return Stream對象 */private staticStream streamOf(Collection collection) {return CollectionUtils.isEmpty(collection) ? Stream.empty() : collection.stream();}/** * 按照映射規(guī)則映射成一個新的集合流 * * @param list集合 * @param mapper 集合屬性元素 * @param函數(shù)輸入類型的泛型 * @param函數(shù)結(jié)果類型的泛型 * @return新的集合 */public staticList mapList(List list, Function mapper) {return streamOf(list).map(mapper).collect(Collectors.toList());}/** * 根據(jù)給定的條件進(jìn)行篩選,將符合條件的元素提取成新的流 * * @param list集合 * @param predicate 篩選規(guī)則 * @param流元素的類型 * @return符合條件的流集合 */public staticList filter(List list, Predicate predicate) {return streamOf(list).filter(predicate).collect(Collectors.toList());}/** * 根據(jù)給定的條件進(jìn)行篩選,將符合條件的元素提取成新的流 * * @param list集合 * @param predicates多個篩選條件 * @param流元素的類型 * @return 符合條件的流集合 */@SafeVarargspublic staticList filters(List list, Predicate … predicates) {Stream stream = streamOf(list);for (Predicate predicate : predicates) {stream = stream.filter(predicate);}return stream.collect(Collectors.toList());}/** * 根據(jù)指定元素對集合進(jìn)行升序排序 * * @param list集合 * @param keyExtractor用來排序的元素 * @param函數(shù)輸入類型的泛型 * @param函數(shù)結(jié)果類型的泛型 * @return排序后的集合 */public static List sorted(List list, Function keyExtractor) {return streamOf(list).sorted(Comparator.comparing(keyExtractor)).collect(Collectors.toList());}/** * 根據(jù)指定元素對集合進(jìn)行升序排序 * * @param list集合 * @param keyExtractor用來排序的元素 * @param limit 排序后集合中保留的數(shù)量 * @param函數(shù)輸入類型的泛型 * @param函數(shù)結(jié)果類型的泛型 * @return排序后的集合 */public static List sorted(List list, Function keyExtractor, Integer limit) {return streamOf(list).sorted(Comparator.comparing(keyExtractor)).limit(limit).collect(Collectors.toList());}/** * 根據(jù)指定元素對集合進(jìn)行降序排序 * * @param list集合 * @param keyExtractor用來排序的元素 * @param函數(shù)輸入類型的泛型 * @param函數(shù)結(jié)果類型的泛型 * @return排序后的集合 */public static List sortedDesc(List list, Function keyExtractor) {return streamOf(list).sorted(Comparator.comparing(keyExtractor).reversed()).collect(Collectors.toList());}/** *根據(jù)規(guī)則判斷元素是否匹配 * * @param list集合 * @param predicate 匹配規(guī)則 * @param元素類型 * @return匹配結(jié)果 */public staticboolean anyMatch(List list, Predicate predicate) {return streamOf(list).anyMatch(predicate);}/** * 將List集合轉(zhuǎn)換成Map集合,同一個key時對value進(jìn)行去重,保留第一個出現(xiàn)的value值 * * @param list集合 * @param keyMapper 新的Map中的key * @param參數(shù)的類型 * @return轉(zhuǎn)換后的Map集合*/public staticMap toMapDistinctFirst(List list, Function keyMapper) {return streamOf(list).collect(Collectors.toMap(keyMapper, Function.identity(), (key1, key2) -> key1));}/** * 將List集合轉(zhuǎn)換成Map集合,同一個key時對value進(jìn)行去重,保留最后出現(xiàn)的value值 * * @param list集合 * @param keyMapper 新的Map中的key * @param參數(shù)的類型 * @return轉(zhuǎn)換后的Map集合*/public staticMap toMapDistinctLast(List list, Function keyMapper) {return streamOf(list).collect(Collectors.toMap(keyMapper, Function.identity(), (key1, key2) -> key2));}/** * 將List轉(zhuǎn)換為指定key->value鍵值對元素的Map集合 * @param list集合 * @param keyMapper Map的key元素 * @param valueMapper Map的value元素 * @param函數(shù)輸入的類型 * @param函數(shù)輸出的類型 * @param函數(shù)輸出的類型 * @return轉(zhuǎn)換后的Map集合*/public staticMap toMap(List list, Function keyMapper,Function valueMapper) {return streamOf(list).collect(Collectors.toMap(keyMapper, valueMapper));}}

    最后希望大家能從文章中得到幫助獲得收獲,也可以評論出你想看哪方面的技術(shù)。文章會持續(xù)更新,希望能幫助到大家,哪怕是讓你靈光一現(xiàn)。喜歡的朋友可以點(diǎn)點(diǎn)贊和關(guān)注,也可以分享出去讓更多的人看見,一起努力一起進(jìn)步!

    鄭重聲明:本文內(nèi)容及圖片均整理自互聯(lián)網(wǎng),不代表本站立場,版權(quán)歸原作者所有,如有侵權(quán)請聯(lián)系管理員(admin#wlmqw.com)刪除。
    上一篇 2022年9月20日 06:12
    下一篇 2022年9月20日 06:13

    相關(guān)推薦

    聯(lián)系我們

    聯(lián)系郵箱:admin#wlmqw.com
    工作時間:周一至周五,10:30-18:30,節(jié)假日休息