Java8 stream處理List,Map總結

Java 8 Stream

Java 8 API添加了一個新的抽象稱為流Stream,可以讓你以一種聲明的方式處理數據。

Stream 使用一種類似用 SQL 語句從數據庫查詢數據的直觀方式來提供一種對 Java 集合運算和表達的高階抽象。

Stream API可以極大提高Java程序員的生產力,讓程序員寫出高效率、干凈、簡潔的代碼。

這種風格將要處理的元素集合看作一種流, 流在管道中傳輸, 并且可以在管道的節點上進行處理, 比如篩選, 排序,聚合等。

元素流在管道中經過中間操作(intermediate operation)的處理,最后由最終操作(terminal operation)得到前面處理的結果。

什么是 Stream?

Stream(流)是一個來自數據源的元素隊列并支持聚合操作

<strong元素隊列< strong="">元素是特定類型的對象,形成一個隊列。 Java中的Stream并不會存儲元素,而是按需計算。

數據源 流的來源。 可以是集合,數組,I/O channel, 產生器generator 等。

聚合操作 類似SQL語句一樣的操作, 比如filter, map, reduce, find, match, sorted等。

和以前的Collection操作不同, Stream操作還有兩個基礎的特征:

Pipelining: 中間操作都會返回流對象本身。 這樣多個操作可以串聯成一個管道, 如同流式風格(fluent style)。 這樣做可以對操作進行優化, 比如延遲執行(laziness)和短路( short-circuiting)。

內部迭代: 以前對集合遍歷都是通過Iterator或者For-Each的方式, 顯式的在集合外部進行迭代, 這叫做外部迭代。 Stream提供了內部迭代的方式, 通過訪問者模式(Visitor)實現。

生成流

在 Java 8 中, 集合接口有兩個方法來生成流:

stream() ? 為集合創建串行流。

parallelStream() ? 為集合創建并行流

下面寫一下,我們經常會用到的一些操作案例

一,排序

  List? ?

   ? 1, 對象集合排序

? ? ? ? //降序,根據創建時間降序;

? ? ? ? List<User> descList = attributeList.stream().sorted(Comparator.comparing(User::getCreateTime, Comparator.nullsLast(Date::compareTo)).reversed()).collect(Collectors.toList());

? ? ? ? //升序,根據創建時間升序;

? ? ? ? List<User> ascList = attributeList.stream().sorted(Comparator.comparing(User::getCreateTime, Comparator.nullsLast(Date::compareTo))).collect(Collectors.toList());

? ? ? ? 2, 數字排序

? ? ? ? List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

? ? ? ? //升序

? ? ? ? List<Integer> ascList = numbers.stream().sorted().collect(Collectors.toList());

? ? ? ? 結果: [2, 2, 3, 3, 3, 5, 7]

? ? ? ? //倒序

? ? ? ? List<Integer> descList = numbers.stream().sorted((x, y) -> y - x).collect(Collectors.toList());

? ? ? ? 結果:[7, 5, 3, 3, 3, 2, 2]

? ? ?  3, 字符串排序

     List<String> strList = Arrays.asList("a", "ba", "bb", "abc", "cbb", "bba", "cab");

? ? ? ? //自然排序

? ? ? ? List<String> ascList = strList.stream().sorted().collect(Collectors.toList());

? ? ? ? 結果:[a, abc, ba, bb, bba, cab, cbb]

? ? ? ? //反轉,倒序

? ? ? ? ascList.sort(Collections.reverseOrder());

? ? ? ? 結果:[cbb, cab, bba, bb, ba, abc, a]

? ? ? ? //直接反轉集合

? ? ? ? Collections.reverse(strList);

? ? ? ? 結果:[cab, bba, cbb, abc, bb, ba, a]

   Map

     //HashMap是無序的,當我們希望有順序地去存儲key-value時,就需要使用LinkedHashMap了,排序后可以再轉成HashMap。

? ? ? ? //LinkedHashMap是繼承于HashMap,是基于HashMap和雙向鏈表來實現的。

? ? ? ? //LinkedHashMap是線程不安全的。

? ? ? ? Map<String,String> map = new HashMap<>();

? ? ? ? map.put("a","123");? ? ? ? map.put("b","456");? ? ? ? map.put("z","789");? ? ? ? map.put("c","234");

? ? ? ? //map根據value正序排序

? ? ? ? LinkedHashMap<String, String> linkedMap1 = new LinkedHashMap<>();

? ? ? ? map.entrySet().stream().sorted(Comparator.comparing(e -> e.getValue())).forEach(x -> linkedMap1.put(x.getKey(), x.getValue()));

? ? ? ? 結果:{a=123, c=234, b=456, z=789}

? ? ? ? //map根據value倒序排序

? ? ? ? LinkedHashMap<String, String> linkedMap2 = new LinkedHashMap<>();? ? map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).forEach(x -> linkedMap2.put(x.getKey(), x.getValue()));

? ? ? ? 結果:{z=789, b=456, c=234, a=123}

? ? ? ? //map根據key正序排序

? ? ? ? LinkedHashMap<String, String> linkedMap3 = new LinkedHashMap<>();

? ? ? ? map.entrySet().stream().sorted(Comparator.comparing(e -> e.getKey())).forEach(x -> linkedMap3.put(x.getKey(), x.getValue()));

? ? ? ? 結果:{a=123, b=456, c=234, z=789}

? ? ? ? //map根據key倒序排序

? ? ? ? LinkedHashMap<String, String> linkedMap4 = new LinkedHashMap<>();? ? ? ? map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey())).forEach(x -> linkedMap4.put(x.getKey(), x.getValue()));

? ? ? ? 結果:{z=789, c=234, b=456, a=123}

二,List 轉 Map

     1、指定key-value,value是對象中的某個屬性值。

? ? ? ? Map<Integer,String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId,User::getName));

? ? ? ? 2、指定key-value,value是對象本身,User->User 是一個返回本身的lambda表達式

? ? ? ? Map<Integer,User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId,User->User));

? ? ? ? 3、指定key-value,value是對象本身,Function.identity()是簡潔寫法,也是返回對象本身

? ? ? ? Map<Integer,User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

? ? ? ? 4、指定key-value,value是對象本身,Function.identity()是簡潔寫法,也是返回對象本身,key 沖突的解決辦法,這里選擇第二個key覆蓋第一個key。

? ? ? ? Map<Integer,User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));

? ? ? ? 5、將List根據某個屬性進行分組,放入Map;然后組裝成key-value格式的數據,分組后集合的順序會被改變,所以事先設置下排序,然后再排序,保證數據順序不變。

? ? ? ? List<GoodsInfoOut> lst = goodsInfoMapper.getGoodsList();

? ? ? ? Map<String, List<GoodsInfoOut>> groupMap = lst.stream().collect(Collectors.groupingBy(GoodsInfoOut::getClassificationOperationId));

? ? ? ? List<HomeGoodsInfoOut> retList = groupMap.keySet().stream().map(key -> {

? ? ? ? ? ? HomeGoodsInfoOut mallOut = new HomeGoodsInfoOut();

? ? ? ? ? ? mallOut.setClassificationOperationId(key);

? ? ? ? ? ? if(groupMap.get(key)!=null && groupMap.get(key).size()>0) {

? ? ? ? ? ? ? ? mallOut.setClassificationName(groupMap.get(key).get(0).getClassificationName());

? ? ? ? ? ? ? ? mallOut.setClassificationPic(groupMap.get(key).get(0).getClassificationPic());

? ? ? ? ? ? ? ? mallOut.setClassificationSort(groupMap.get(key).get(0).getClassificationSort());

? ? ? ? ? ? }

? ? ? ? ? ? mallOut.setGoodsInfoList(groupMap.get(key));

? ? ? ? ? ? return mallOut;

? ? ? ? }).collect(Collectors.toList());

? ? ? ? List<HomeGoodsInfoOut> homeGoodsInfoOutList = retList.stream().sorted(Comparator.comparing(HomeGoodsInfoOut::getClassificationSort))

.collect(Collectors.toList());

? ? ? 5、根據用戶性別將數據 - 分組

     Map<String, List<UserInfo>> groupMap = userList.stream().collect(Collectors.groupingBy(UserInfo::getSex()));

? ? ? 6、List實體轉Map,想要有序的話,就使用以下操作(TreeMap 有序;Map 無序)

     TreeMap<String, List<BillPollEntity>> ascMonthBillPollMap = s.stream().collect(Collectors.groupingBy(t -> t.getDrawTime()), TreeMap::new, Collectors.toList()));

     //倒敘MAP

? ? ? ? NavigableMap<String, List<OpenActivityOut>> descMonthBillPollMap = ascMonthBillPollMap.descendingMap();

     Map<String, List<BillPollEntity>> monthBillPollMap = s.stream().collect(Collectors.groupingBy(BillPollEntity::getDrawTime));

三,Map 轉 List

     Map<String,String> map1 = new HashMap<>();

? ? ? ? map1.put("a","123");

? ? ? ? map1.put("b","456");

? ? ? ? map1.put("z","789");

? ? ? ? map1.put("c","234");

? ? ? ? 1、默認順序

? ? ? ? List<UserInfo> list0 = map1.entrySet().stream()

                   .map(e -> new UserInfo(e.getValue(), e.getKey()))

                   .collect(Collectors.toList());

? ? ? ? 結果:[UserInfo(userName=123, mobile=a), UserInfo(userName=456, mobile=b), UserInfo(userName=234, mobile=c), UserInfo(userName=789, mobile=z)]

? ? ? ? 2、根據Key排序

? ? ? ? List<UserInfo> list1 = map1.entrySet().stream()

                   .sorted(Comparator.comparing(e -> e.getKey())).map(e -> new UserInfo(e.getKey(), e.getValue()))

                   .collect(Collectors.toList());

? ? ? ? 結果:[UserInfo(userName=a, mobile=123), UserInfo(userName=b, mobile=456), UserInfo(userName=c, mobile=234), UserInfo(userName=z, mobile=789)]

? ? ? ? 3、根據Value排序

? ? ? ? List<UserInfo> list2 = map1.entrySet().stream()

                  .sorted(Comparator.comparing(Map.Entry::getValue))

                  .map(e -> new UserInfo(e.getKey(), e.getValue()))

                  .collect(Collectors.toList());

? ? ? ? 結果:[UserInfo(userName=a, mobile=123), UserInfo(userName=c, mobile=234), UserInfo(userName=b, mobile=456), UserInfo(userName=z, mobile=789)]

? ? ? ? 3、根據Key排序

? ? ? ? List<UserInfo> list3 = map1.entrySet().stream()

                  .sorted(Map.Entry.comparingByKey())

                  .map(e -> new UserInfo(e.getKey(), e.getValue()))

                  .collect(Collectors.toList());

? ? ? ? 結果:[UserInfo(userName=a, mobile=123), UserInfo(userName=b, mobile=456), UserInfo(userName=c, mobile=234), UserInfo(userName=z, mobile=789)]

     4、Map<String,UserInfo> 轉 List<String>、List<UserInfo>

      // 取Map中的所有value

      結果:List<UserInfo> userInfoList = retMap.values().stream().collect(Collectors.toList());

      // 取Map中所有key

      結果:List<String> strList = retMap.keySet().stream().collect(Collectors.toList());

四,從List中獲取某個屬性

//拿出所有手機號

List<String> mobileList = userList.stream().map(RemindUserOut::getMobile).collect(Collectors.toList());

//拿出所有AppId,并去重

List<String> appIdList = appIdList.stream().map(WechatWebViewDomain::getAppId).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());

//拿出集合中重復的billNo,【.filter(map->StringUtils.isNotEmpty(map.getBillNo()))】這是過濾掉為空的數據;否則,有空數據會拋異常

List<String> repeatCodeList = resultList.stream().filter(map->StringUtils.isNotEmpty(map.getBillNo())).collect(Collectors.groupingBy(BillUploadIn::getBillNo, Collectors.counting())).entrySet().stream().filter(entry -> entry.getValue() > 1).map(Map.Entry::getKey).collect(Collectors.toList());

//拿出集合中幾個屬性拼接后的字符串

List<String> strList = myList.stream().map(p -> p.getName() + "-" + p.getMobile()).collect(Collectors.toList());

五,篩選并根據屬性去重

List<UserInfo> uList = new ArrayList<>();

UserInfo u1 = new UserInfo(1,"小白","15600000000");

UserInfo u2 = new UserInfo(2,"小黑","15500000000");

uList.add(u1);

uList.add(u2);

//過濾名字是小白的數據

List list1= uList.stream()

.filter(b -> "小白".equals(b.getUserName()))

.collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(b -> b.getId()))), ArrayList::new));

結果:list1===[UserInfo(id=1, userName=小白, mobile=15600000000)]

//根據ID去重

List list2= uList.stream()

.collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(b -> b.getId()))), ArrayList::new));

結果:list2===[UserInfo(id=1, userName=小白, mobile=15600000000), UserInfo(id=2, userName=小黑, mobile=15500000000)]

? //整個數據去重

? list = list.stream().distinct().collect(Collectors.toList());

六,計算;和,最大,最小,平均值。

List<UserInfo> uList = new ArrayList<>();

UserInfo user1 = new UserInfo(1,"小白","15600000000",10,new BigDecimal(10));

UserInfo user2 = new UserInfo(2,"小黑","15500000000",15,new BigDecimal(20));

UserInfo user3 = new UserInfo(2,"小彩","15500000000",88,new BigDecimal(99));

uList.add(user1);

uList.add(user2);

uList.add(user3);

//和

Double d1 = uList.stream().mapToDouble(UserInfo::getNum).sum();

結果:113.0

//最大

Double d2 = uList.stream().mapToDouble(UserInfo::getNum).max().getAsDouble();

結果:88.0

//最小

Double d3 = uList.stream().mapToDouble(UserInfo::getNum).min().getAsDouble();

結果:10.0

//平均值

Double d4 = uList.stream().mapToDouble(UserInfo::getNum).average().getAsDouble();

結果:37.666666666666664

//除了統計double類型,還有int和long,bigDecimal需要用到reduce求和

DecimalFormat df = new DecimalFormat("0.00");//保留兩位小數點

//和;可過濾掉NULL值

BigDecimal add = uList.stream().map(UserInfo::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);

BigDecimal add = uList.stream().filter(s->t.getPrice()!=null).map(UserInfo::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add)

System.out.println(df.format(add));

結果:129.00

//最大

Optional<UserInfo> max = uList.stream().max((u1, u2) -> u1.getNum().compareTo(u2.getNum()));

System.out.println(df.format(max.get().getPrice()));

結果:99.00

//最小

Optional<UserInfo> min = uList.stream().min((u1, u2) -> u1.getNum().compareTo(u2.getNum()));

System.out.println(df.format(min.get().getPrice()));

結果:10.00

//求和,還有mapToInt、mapToLong、flatMapToDouble、flatMapToInt、flatMapToLong

list.stream().mapToDouble(UserInfo::getNum).sum();

//最大

list.stream().mapToDouble(UserInfo::getNum).max();

//最小

list.stream().mapToDouble(UserInfo::getNum).min();

//平均值

list.stream().mapToDouble(UserInfo::getNum).average();

//獲取N個List中,最大數組長度

List<OrderExcelOut> valueList = new ArrayList<>();

List<List<TagOut>> tagList = valueList.stream().filter(v -> v.getTagList() != null && v.getTagList().size() > 0).map(OrderExcelOut::getTagList).collect(Collectors.toList());

Optional<List<TagOut>> maxTagList = tagList.stream().max((u1, u2) -> Integer.valueOf(u1.size()).compareTo(u2.size()));

//數組中最長的數組

maxTagList.get().size();

————————————————

版權聲明:本文為CSDN博主「征塵bjajmd」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。

原文鏈接:https://blog.csdn.net/y19910825/article/details/128107210

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,333評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,491評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,263評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,946評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,708評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,186評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,255評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,409評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,939評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,774評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,976評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,518評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,209評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,641評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,872評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,650評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,958評論 2 373

推薦閱讀更多精彩內容