如何对 Map<LocalDate, Integer> 进行排序?

How can I sort a Map<LocalDate, Integer>?

我只想知道如何按时间顺序对 Map.

进行排序

这是我的代码的第一行:

Map<LocalDate, Integer> commitsPerDate = new HashMap<>();

之后,我用任何值(但不是按时间顺序)填充我的地图。 当我显示我的地图的值时,它按以下顺序显示:

for(var item : commitsPerDate.entrySet()) {
     System.out.println(item.getKey() + " = " + item.getValue());
}
2020-08-31 = 1
2020-09-30 = 3
2020-09-29 = 1
2020-09-28 = 5
2020-09-27 = 5
2020-08-27 = 4
2020-09-25 = 3
2020-10-21 = 1
2020-10-18 = 1
2020-10-17 = 5
2020-10-16 = 4
2020-10-15 = 5
2020-10-14 = 6
2020-09-14 = 1
2020-10-13 = 2
2020-09-13 = 2

而且我希望它按时间顺序排序,以便显示顺序相同。

谢谢。

一样,如果您希望地图按键对元素进行排序,则可以使用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"), 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-09-30=3, 2020-09-29=1, 2020-09-28=5, 2020-08-31=1}

出于任何原因,如果您必须使用 HashMap,请检查 How to sort Map values by key in Java?