[英]Merging keys of a HashMap
我正在從數據庫中獲取數據並制作 map,如下所示:
List<MyBO> data = callDatabase();
//here I am grouping the channels by run date
Map<String, List<String>> groupDatesByChannel = data .parallelStream().collect(
Collectors.groupingBy(MyBO::getChannelName,
Collectors.mapping(MyBO::getRunDate, Collectors.toList())));
現在的問題是,對於其中一個通道,運行日期是每小時一次,即通道上的批處理每小時運行一次,因此從數據庫中獲取的特定源運行日期的形式是 yyyyMMddHH,而不是 yyyyMMdd。
我的代碼適用於運行日期為 yyyMMdd 格式的頻道,我上面的 map 示例(groupDatesByChannel)如下:
Channel_2[20200101 , 20200103 , 20200107],
Channel_5[20200103 ]
Channel_7[20200102 , 20200104 ]
我想為每小時運行日期的頻道制作此映射。
Channel_1[**2020010100,2020010101...2020010123,20200101**, 20200102, 20200104 ],
Channel_2[20200101 , 20200103 , 20200107],
Channel_5[20200103 ]
Channel_7[20200102 , 20200104 ]
至
Channel_1[**20200101**, 20200102, 20200104 ],
Channel_2[20200101 , 20200103 , 20200107],
Channel_5[20200103 ]
Channel_7[20200102 , 20200104 ]
即我想合並所有相同的日期,無論是在 yyyyMMddHH 還是 yyyyMMdd fromat。
以下代碼經過測試並且工作正常。
public static Map<String, List<String>> mergeData(Map<String, List<String>> originalData){
Map<String, List<String>> mergedData = new HashMap<String, List<String>>();
for(String key : originalData.keySet()){
// Cleaning the key string. Removing *'s
String trimmedKey = key.replaceAll("\\*","");
// Trimming the key string. Trimming the hour digits, so that key will only contain date value
String dateOnlyKey = trimmedKey.substring(0,8);
// If mergedData already has the key, add values to the list.
if(mergedData.containsKey(dateOnlyKey)){
// Adding directly to the list may create duplicate entries. So, appending all data to HashSet and writing back to list
// If having duplicates is ok, next two lines can be ommitted and third line would be mergedData.get(dateOnlyKey).addAll(originalData.get(key));
Set<String> channels = new HashSet<String>(mergedData.get(dateOnlyKey));
channels.addAll(originalData.get(key));
mergedData.put(dateOnlyKey, new ArrayList<String>(channels));
}
// If mergedData doesn't have the key, add the new entry
else{
mergedData.put(dateOnlyKey, originalData.get(key));
}
}
System.out.println(mergedData.entrySet());
return mergedData;
}
邏輯很簡單
您可以運行代碼並自行檢查。 對我來說工作得很好。
實現這一目標的最簡單方法是僅將 DateTime 的前 8 個字符用於分組。
Map<String, List<String>> groupDatesByChannel = data .parallelStream().collect(
Collectors.groupingBy(myBO -> myBO.getChannelName().substring(0,8),
Collectors.mapping(MyBO::getRunDate, Collectors.toList())));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.