java 8 java demo_Java 8 中的 Streams API Demo
Java8 Streams demo
一、獲取List集合中的某個字段的List集合
例如:
List userIdList = payBillVOList.stream().mapToLong(PayBillVO::getUserId).boxed().collect(Collectors.toList());
before java8 :
List userIdList = new ArrayList<>();
for (PayBillVO payBillVO : payBillVOList) {
userIdList.add(payBillVO.getUserId());
}
List集合中的某個字段轉為String
String appIds = Joiner.on(",").join(deviceUserDOList.stream().map(TDeviceUserDO::getAppId).distinct().collect(Collectors.toList()));
二、List對象轉Map
例如:
單個對象:
Map userMainMap = userMainList.stream().collect(Collectors.toMap(UserMain::getUserId, c -> c));
List對象:
Map> collectionVOListMap = collectionVOList.stream().collect(Collectors.groupingBy(CollectionVO::getCreateDate));
before java8 :
自己寫很復雜。
三、String按特定的規則轉List
例如:
基礎版本:withdrawInfoIds=110,120
List withdrawInfoIdList = Splitter.on(",").splitToList(withdrawInfoIds).stream().mapToLong(Long::valueOf).boxed().collect(Collectors.toList());
兼容版本:relationMobileIds=110,,120,
List relationIdList = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(relationMobileIds).stream().mapToLong(Long::valueOf).boxed().collect(Collectors.toList());
before java8 :
List withdrawInfoIdList = new ArrayList<>();
String[] withdrawInfoIdArr = withdrawInfoIds.split(",");
for (String id : withdrawInfoIdArr) {
withdrawInfoIdList.add(Long.valueOf(id));
}
四、獲取list集合中某個字段出現的總數(例如統計用戶ID出現的次數)
例如:
Map withdrawInfoListMap = withDrawInfoDOList.stream().collect(Collectors.groupingBy(TWithDrawInfoDO::getUserId, Collectors.counting()));
五、List集合中的對象轉為另一個對象
例如:
List entryAPIList = entryDOList.getContent().stream().map(EntryVO::toVoFromDo).collect(Collectors.toList());
其中:
public static EntryVO toVoFromDo(EntryDO entryDO){
if (entryDO == null){
return null;
}
return new EntryVO(entryDO.getAutoId(), entryDO.getUserId());
}
六、從list集合中篩選出符合條件的一條記錄
例如:
Long entryId = 8;
EntryAPI entryAPI = entryAPIList.stream().filter(p -> p.getAutoId().equals(entryId)).findFirst().orElse(null);
七、排序
例如:先排序,再格式化輸出
List openTimeList;
List openTimeStringList = openTimeList.stream().sorted(Comparator.comparing(date -> date)).map((date)-> DateUtils.formatHourMinutes(date)).collect(Collectors.toList());
例如:把list集合中的數據轉成String輸出 空格隔開
List openTimeStringList
String openTimeString = openTimeStringList.stream().collect(Collectors.joining(" "));
八、求和
Integer point = billPointsDOList.stream().mapToInt(TBillPointsDO::getTotalPointsAvaliable).sum();
BigDecimal paidAmount = billPaymentDOList.stream().map(TBillPaymentDO::getPayment).reduce(BigDecimal.ZERO, BigDecimal::add);
總結
以上是生活随笔為你收集整理的java 8 java demo_Java 8 中的 Streams API Demo的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: xcat 安装(liunx高性能刀片集群
- 下一篇: xCAT2安装配置