【问题标题】:How can I sort a Map<LocalDate, Integer>? [duplicate]如何对 Map<LocalDate, Integer> 进行排序? [复制]
【发布时间】:2021-02-07 20:34:41
【问题描述】:

我只想知道如何按时间顺序对 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

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

谢谢。

【问题讨论】:

  • 如果你想通过 key 对元素进行映射,那么你可以使用 TreeMap 而不是 HashMap。

标签: java sorting dictionary hashmap chronological


【解决方案1】:

作为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"), 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?

【讨论】:

    猜你喜欢
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多