我的 HashMap 中有两个数组,我想根据 timeStampArray
中的时间对存储在 averageValueArray
中的值进行排序。尝试使用 TreeMap 但弄得一团糟。
任何帮助将不胜感激。
Map<List<Date>,List<Double>> unsortedMap = new HashMap<List<Date>,List<Double>>();
unsortedMap.put(timeStampArray, averageValueArray);
这就是我想要的
Map<List<Date>,List<Double>> sortMap = new HashMap<List<Date>,List<Double>>();
sortMap.put(timeStampArray, averageValueArray);
for (Map.Entry entry : sortMap.entrySet()) {
System.out.println("Key = " + entry.getKey());
System.out.println(" Value = " +entry.getValue());
}
System.out.println("Unsort Map......");
printMap(sortMap);
System.out.println("Sorted Map......");
Map<List<Date>,List<Double>> treeMap = new TreeMap<List<Date>,List<Double>>(sortMap);
printMap(treeMap);
和 printMap 为:
public static void printMap(Map<List<Date>,List<Double>> map) {
for (Map.Entry entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());}}
最佳答案
如果我没理解错的话,你有两个平行列表,一个包含时间,另一个包含平均值。并且您希望这两个列表“并行”排序。
你最好有一个对象列表,每个对象包含一个日期和一个平均值,然后根据需要对该列表进行排序:
public final class DatedAverage {
private final Date date;
private final double average;
// constructor, getters omitted
}
...
List<DatedAverage> datedAverages = ...;
Collections.sort(datedAverages, new Comparator<DatedAverage>() {
@Override
public int compare(DatedAverage d1, DatedAverage d2) {
return d1.getDate().compareTo(d2.getDate());
}
});
Java 是一种面向对象的语言。使用对象,并将行为封装在这些对象中。
关于java - 排序 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16872296/