This will do what you want:
Map<String,Integer> map = new HashMap<String, Integer>(){{ put("cat", 2); put("dog", 1); put("llama", 0); put("iguana", -1); }};
This statement creates an anonymous subclass of HashMap, where the only difference from the parent class is that 4 entries are added when the instance is created. This is a fairly common idiom in the Java world (although some find it inconsistent because it creates a new class definition).
Because of this dispute, with Java 9, there is a new idiom for convenient map building: a family of static Map.of methods .
Using Java 9 or higher, you can create the required map as follows:
Map<String, Integer> map = Map.of( "cat", 2, "dog", 1, "llama", 0, "iguana", -1 );
With larger cards, this alternative syntax may be less error prone:
Map<String, Integer> map = Map.ofEntries( Map.entry("cat", 2), Map.entry("dog", 1), Map.entry("llama", 0), Map.entry("iguana", -1) );
(This is especially good if Map.entry is statically imported rather than explicitly specified).
Besides working with Java 9+, these new approaches are not quite equivalent to the previous one:
- They do not allow you to specify which map implementation is used.
- They only create immutable cards
- They do not create an anonymous subclass of Map
However, these differences should not be significant for many use cases, which makes this approach a good default for newer versions of Java.