微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何排序Map <LocalDate,Integer>?

如何解决如何排序Map <LocalDate,Integer>?

我只想了解如何按年代顺序对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?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。