如何在Map Hashmap Java中对月份进行排序

  • 本文关键字:排序 Map Hashmap Java java
  • 更新时间 :
  • 英文 :


在Java哈希图上将月份作为键时,我遇到了麻烦。 有人可以帮助我吗?

我想显示: {1 月=0.0,2 月=0.0,3 月=0.0,4 月=0.0}

但是,代码的结果是: {3 月=0.0,1 月=0.0,2 月=0.0,4 月=0.0}

这是我的代码。

import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Double> capitalCities = new HashMap<String,Double>();
capitalCities.put("January", 0.0);
capitalCities.put("February", 0.0);
capitalCities.put("March", 0.0);
capitalCities.put("April", 0.0);
System.out.println(capitalCities); 
}
}

我为此苦苦挣扎,请帮忙

据我所知,您的方法有两个问题。

首先,HashMap不会按任何特定顺序对其条目进行排序。 如果循环访问Map,则未指定条目的显示顺序。

要克服这个问题,您应该使用 另一种Map.TreeMap应符合您的要求,因为它按顺序存储其条目。

第二个问题是,默认情况下,String值将按字母顺序排序,但您实际上希望按日历顺序对月份进行排序。 可以通过使用java.time包中的Month枚举作为Map的键来解决此问题。

如果修复了这两个问题,代码将如下所示。

Map<Month,Double> capitalCities = new TreeMap<>();
capitalCities.put(Month.JANUARY, 0.0);
capitalCities.put(Month.FEBRUARY, 0.0);

等等。

附录:亚历山大·伊万琴科使用EnumMap的解决方案比这个更好。

正如@Dawood伊本·卡里姆(ibn Kareem)在他的答案中指出的那样,java.time包中的枚举Month比使用普通String更好。

我想补充一点,从 Java 5 开始,我们有一个特殊用途的Map接口实现 -EnumMap,它保持其条目根据用作enum的自然顺序排序。

下面是一个示例:

Map<Month, Double> valueByMonth = new EnumMap<>(Month.class);
valueByMonth.put(Month.JULY, 9.3);
valueByMonth.put(Month.APRIL, 4.8);
valueByMonth.put(Month.FEBRUARY, 3.9);
valueByMonth.put(Month.JANUARY, 1.0);
valueByMonth.put(Month.MARCH, 4.5);

valueByMonth.forEach((k, v) -> System.out.println(k + " -> " + v)); // printing map's contents

输出:

JANUARY -> 1.0
FEBRUARY -> 3.9
MARCH -> 4.5
APRIL -> 4.8
JULY -> 9.3

最新更新