使用java8將list轉為map


1、Map

map:對集合中的元素逐個進行函數操作映射成另外一個

 

List<String> nidList = resultList.stream().map(TrackNoOverTimeDto::getNid).collect(Collectors.toist());

//String類型轉Int
List<Integer> nidIntList = nidList.stream().map(Integer::parseInt).collect(Collectors.toList());

List<Integer> modelIds = Arrays.asList(modelIdStr.trim().split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());

 

 

 

 

 

2、flatMap

flatMap:接收一個函數作為參數,將流中的每個值都轉換為另一個流,然后把所有的流都連接成一個流。

 

// 列表的屬性本身是一個集合,收集這個集合屬性,形成一個大的集合
// params是SpuSpecificationParam的一個集合 // specValues是SpuSpecificationParam的一個集合屬性 List<SpuSpecificationParam.SpuSpecValue> collect = params.stream().map(SpuSpecificationParam::getSpecValues).flatMap(item -> item.stream()).collect(Collectors.toList());

 

 

3、Collectors.toMap

//案例1:收集Account的id作為key,username作為value,形成一個Map
public Map<Long, String> getIdNameMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
}

//案例2:收集Account的id作為key,對應的List元素作為作為value
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}

public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
    //account -> account是一個返回本身的lambda表達式,可以使用Function接口中的一個默認方法代替,使整個方法更簡潔優雅
    return accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity()));
}


//案例3:自定義Key
Map<String, SalesPurchaseDailyStatistics> existStatisticsMap = 
      existStatisticsList.stream().collect(Collectors.toMap(item -> item.getStatisticsDay() + "_" + item.getUserName(), Function.identity()));

//案例4:自定義Key
Map<String, TOwpAmazon> tOwpAmazonMap = tOwpAmazonList.stream().collect(Collectors.toMap(item -> item.getId().toString(), Function.identity()));

3.1 重復key的問題

toMap可能報錯(java.lang.IllegalStateException: Duplicate key),因為key是有可能重復的。toMap有個重載方法,可以傳入一個合並的函數來解決key沖突問題:

public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}

//這里只是簡單的使用后者覆蓋前者來解決key重復問題。還有一種分組的方法:
Map<Long, List<ActivityUserMissionDO>> map = activityUserMissionDos.stream().collect(Collectors.groupingBy(ActivityUserMissionDO::getParentModuleId));

 

3.2 指定具體收集的map

//toMap還有另一個重載方法,可以指定一個Map的具體實現,來收集數據:
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));
}

 

4、分組

Map<Integer, List<PyTradeOrderDt>> orderMap = pyTradeOrderDts.stream().collect(Collectors.groupingBy(PyTradeOrderDt::getTradeNid));

orderMap.forEach((k, v) -> {
    Set<String> collect = v.stream().map(PyTradeOrderDt::getSku).collect(Collectors.toSet());
    skuSet.addAll(collect);
});

//按多個屬性分組
Map<String, List<JsonObject>> menuGroupMap = list.stream().collect(Collectors.groupingBy(goods -> goods.getInteger("menu_id")+"_"+goods.getString("menu_name")));

 

排序

 List<TrackNoOverTimeDto> resultList = new ArrayList<>();
 
 resultList.forEach(item ->{
    List<PyTradeLogs> pyTradeLogs = collect.get(item.getNid());

    //取出日志ID最大的記錄
    PyTradeLogs tradeLogs = pyTradeLogs.stream().sorted((s1, s2) -> {
        if (s1.getOpDate() != null && s2.getOpDate() != null) {
            //如果日期都有值,按日期排序
            return -s1.getOpDate().compareTo(s2.getOpDate());
        } else if (s1.getOpDate() == null && s2.getOpDate() == null) {
            //如果日期都沒有值,按主鍵ID排序
            return -s1.getNID().compareTo(s2.getNID());
        } else if (s1.getOpDate() == null && s2.getOpDate() != null) {
            //opDate為null的放在最后
            return 1;
        } else if (s1.getOpDate() != null && s2.getOpDate() == null) {
            //opDate為null的放在最后
            return -1;
        }
        return -s1.getNID().compareTo(s2.getNID());
    }).findFirst().get();
});

 

 Filter

List<ChargerCluster> unSmartChargingClusters = chargerClusterList.stream().filter(item -> item.getSmartCharging() == null || !item.getSmartCharging()).collect(Collectors.toList());

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM