I got trouble when put month as key on Java hashmap. Can someone help me?
I want to display : {January=0.0, February=0.0, March=0.0, April=0.0}
But, the result from the code is : {March=0.0, January=0.0, February=0.0, April=0.0}
This is my code..
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);
}
}
I'm so struggling about it, please help
CodePudding user response:
There are two problems with your approach, as far as I can see.
The first is that a HashMap
doesn't sort its entries in any particular order. It's not specified which order the entries will appear in, if you iterate through the Map
.
To overcome this, you should use a different kind of Map
. A TreeMap
should fit your requirement, as it stores its entries in order.
The second problem is that by default, String
values will be sorted alphabetically, but you actually want to sort the months in calendar order. You can get around this by using the Month
enumeration in the java.time
package, as the key for your Map
.
If you fix both these issues, the code will look something like this.
Map<Month,Double> capitalCities = new TreeMap<>();
capitalCities.put(Month.JANUARY, 0.0);
capitalCities.put(Month.FEBRUARY, 0.0);
and so on.
Addendum: Alexander Ivanchenko's solution using EnumMap
is better than this one.
CodePudding user response:
As @Dawood ibn Kareem has pointed out in his answer enum Month
from java.time
package is better option than using a plain String
.
I want to add that since Java 5 we have a special purpose implementation of the Map
interface - EnumMap
, which maintain its entries sorted according to the natural order of enum
used as a key.
Here's an example:
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
Output:
JANUARY -> 1.0
FEBRUARY -> 3.9
MARCH -> 4.5
APRIL -> 4.8
JULY -> 9.3