Java 8 中的 Streams API Demo

Java8 Streams demo

一、获取List集合中的某个字段的List集合

例如:

List<Long> userIdList = payBillVOList.stream().mapToLong(PayBillVO::getUserId).boxed().collect(Collectors.toList());

before java8 :

List<Long> 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<Long, UserMain> userMainMap = userMainList.stream().collect(Collectors.toMap(UserMain::getUserId, c -> c));

List对象:

Map<String, List<CollectionVO>> collectionVOListMap = collectionVOList.stream().collect(Collectors.groupingBy(CollectionVO::getCreateDate));

before java8 :

自己写很复杂。

三、String按特定的规则转List

例如:

基础版本:withdrawInfoIds=110,120

List<Long> withdrawInfoIdList = Splitter.on(",").splitToList(withdrawInfoIds).stream().mapToLong(Long::valueOf).boxed().collect(Collectors.toList());

兼容版本:relationMobileIds=110,,120,

List<Long> relationIdList = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(relationMobileIds).stream().mapToLong(Long::valueOf).boxed().collect(Collectors.toList());

before java8 :

List<Long> withdrawInfoIdList = new ArrayList<>();
String[] withdrawInfoIdArr = withdrawInfoIds.split(",");
for (String id : withdrawInfoIdArr) {
      withdrawInfoIdList.add(Long.valueOf(id));
} 

四、获取list集合中某个字段出现的总数(例如统计用户ID出现的次数)

例如:

Map<Long, Long> withdrawInfoListMap = withDrawInfoDOList.stream().collect(Collectors.groupingBy(TWithDrawInfoDO::getUserId, Collectors.counting()));

五、List集合中的对象转为另一个对象

例如:

List<EntryVO> 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<Date> openTimeList;
List<String> openTimeStringList = openTimeList.stream().sorted(Comparator.comparing(date -> date)).map((date)-> DateUtils.formatHourMinutes(date)).collect(Collectors.toList());

例如:把list集合中的数据转成String输出 空格隔开

List<String> 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);

    原文作者:夏凯
    原文地址: https://blog.csdn.net/jiaocaigeng/article/details/77258723
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞