By Alvin Alexander. Last updated: October 7, 2020
Java FAQ: How do I populate (initialize) a static HashMap in Java?
In Java 9 and newer you can create and populate a Map
like this:
Map<String, String> peeps = Map.of( "Captain", "Kirk", "Mr.", "Spock" );
This approach also works:
Map<> peeps = new HashMap<String, String>(Map.of( "Captain", "Kirk", "Mr.", "Spock" ));
Create and populate a Map prior to Java 9
If you need to initialize/populate a Map/HashMap in Java prior to Java 9 — such as when you’re writing Android code — the following source code shows the proper syntax:
/** * Off Tackle Run vs 3-4 Defense [Yardage Gained -> Probability] */ public static final Map<Integer, Float> RunOffTackle_34Defense = new HashMap<Integer, Float>() {{ put(-99, 1f); //1 fumble per 100 hand-offs put(-1, 4f); put( 0, 5f); put( 1, 9f); put( 2, 11f); put( 3, 15f); put( 4, 15f); put( 5, 11f); put( 6, 9f); put( 7, 5f); put( 8, 4f); put( 9, 3f); put(10, 3f); put(12, 2f); put(15, 2f); put(20, 1f); }};
As you can see, this syntax lets me add static, predefined data to my Java Map
/HashMap
. I use this approach in a Java/Android football game that I’m currently writing. The important thing that this example shows is how to add data to a HashMap
when you first create/define the HashMap
(i.e., how to initialize it).