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>> monthBillPollMap = s.stream().collect(Collectors.groupingBy(t -> t.getDrawTime()), TreeMap::new, Collectors.toList()));
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)]
四,從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<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();
未完,待續...
