Programming Tips - Java: How to initialize a HashMap

Date: 2012sep22 Update: 2025sep27 Language: Java Keywords: init Q. Java: How to initialize a HashMap A. Here is a nice way to do it. Show as a full example:
import java.util.HashMap; class Demo { static HashMap<String,String> fruitToColor = new HashMap<>() {{ put("apple", "red"); put("orange", "orange"); put("banana", "yellow"); }}; // Notice the double brace brackets. public static final void main(String []args) { for (var entry : fruitToColor.entrySet()) { System.out.println("entry is " + entry); } } }
Output:
entry is orange=orange entry is banana=yellow entry is apple=red
Some people don't like the double brace brackets because it creates an anonymous inner class. But I like it because its compact.