我有這樣的地圖:
Map<Date, List<T>> data = new HashMap<Date, List<T>>();
在 for 回圈中,資料被添加到這個資料映射中。
現在我必須將整個 Map 的 Value 列合并到單個List<T>. 合并應該基于資料的 Key 以升序進行。
我寫了一個這樣的 foreach 回圈:
List<T> newData = new List<T>();
Iterator<Map.Entry<Date , List<T>>> itr = data.entrySet().iterator();
while(itr.hasNext())
{
Map.Entry<date, List<T>> entry = itr.next();
newData.addAll(entry.getValue());
}
在添加到newData變數之前,如何按日期(鍵)進行此訂單。任何幫助都受到高度贊賞。
uj5u.com熱心網友回復:
使用流管道要容易得多,它可以讓您在一個陳述句中同時完成:
List<T> newData = data.entrySet().stream()
.sorted(Entry.comparingByKey())
.map(Entry::getValue)
.flatMap(List::stream)
.collect(Collectors.toList());
Entry.comparingByKey() 將提供一個使用鍵(您的日期物件)對流進行排序的比較器。
請注意,您的T物件將僅根據Date它們對應的鍵包含在結果串列中,結果串列中不會對T值進行任何排序(除非它們已經在最初添加到地圖的所有較小串列中進行了排序)。
uj5u.com熱心網友回復:
// 如果您有一個現有的“資料”哈希圖。否則,您可以直接添加到 TreeMap 中。
TreeMap<Date, List<T>> yourSortedMap = new TreeMap<>(data);
Iterator<Map.Entry<Date , List<T>>> itr = yourSortedMap.entrySet().iterator();
while(itr.hasNext())
{
Map.Entry<date, List<T>> entry = itr.next();
newData.addAll(entry.getValue());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/313183.html
