Programming Tips - Java: How to initialize a HashMap

Date: 2012sep22 Update: 2025jul13 Language: Java Keywords: init Q. Java: How to initialize a HashMap A. Here is a nice way to do it:
HashMap<String,String> fruitToColor = new HashMap<String, String>() {{ put("apple", "red"); put("orange", "orange"); put("banana", "yellow"); }}; // Notice the double brace brackets.
Some people don't like the double brace brackets because it creates an anonymous inner class. But I like it because its compact.