问题描述
我只想了解如何按年代顺序对Map
这是我的代码的第一行:
print
然后,我用任何值(但不按时间顺序)填写地图。 当我显示地图的值时,它会按以下顺序显示:
Map<LocalDate,Integer> commitsPerDate = new HashMap<>();
for(var item : commitsPerDate.entrySet()) {
System.out.println(item.getKey() + " = " + item.getValue());
}
我希望按时间顺序对其进行排序,以便显示顺序相同。
谢谢。
解决方法
与Pshemo has already mentioned一样,如果您希望地图按键对元素进行排序,则可以使用TreeMap
代替HashMap
。
演示:
import java.time.LocalDate;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map<LocalDate,Integer> commitsPerDate = new TreeMap<>();
commitsPerDate.put(LocalDate.parse("2020-08-31"),1);
commitsPerDate.put(LocalDate.parse("2020-09-30"),3);
commitsPerDate.put(LocalDate.parse("2020-09-29"),1);
commitsPerDate.put(LocalDate.parse("2020-09-28"),5);
System.out.println(commitsPerDate);
}
}
输出:
{2020-08-31=1,2020-09-28=5,2020-09-29=1,2020-09-30=3}
以相反的顺序:
import java.time.LocalDate;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
Map<LocalDate,Integer> commitsPerDate = new TreeMap<>(Collections.reverseOrder());
commitsPerDate.put(LocalDate.parse("2020-08-31"),5);
System.out.println(commitsPerDate);
}
}
输出:
{2020-09-30=3,2020-08-31=1}
出于任何原因,如果必须使用HashMap
,请选中How to sort Map values by key in Java?