Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This will do what you want:</p> <pre><code>Map&lt;String,Integer&gt; map = new HashMap&lt;String, Integer&gt;(){{ put("cat", 2); put("dog", 1); put("llama", 0); put("iguana", -1); }}; </code></pre> <p>This statement creates an anonymous subclass of HashMap, where the only difference from the parent class is that the 4 entries are added during instance creation. It's a fairly common idiom in the Java world (although some find it controversial because it creates a new class definition).</p> <p>Because of this controversy, as of Java 9 there is a new idiom for conveniently constructing maps: the family of static <a href="https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#of-K-V-" rel="nofollow noreferrer">Map.of methods</a>.</p> <p>With Java 9 or higher you can create the map you need as follows:</p> <pre><code>Map&lt;String, Integer&gt; map = Map.of( "cat", 2, "dog", 1, "llama", 0, "iguana", -1 ); </code></pre> <p>With larger maps, this <a href="https://docs.oracle.com/javase/9/docs/api/java/util/Map.html#ofEntries-java.util.Map.Entry...-" rel="nofollow noreferrer">alternative syntax</a> may be less error-prone:</p> <pre><code>Map&lt;String, Integer&gt; map = Map.ofEntries( Map.entry("cat", 2), Map.entry("dog", 1), Map.entry("llama", 0), Map.entry("iguana", -1) ); </code></pre> <p>(This is especially nice if Map.entry is statically imported instead of being referenced explicitly).</p> <p>Besides only working with Java 9+, these new approaches are not quite equivalent to the previous one:</p> <ul> <li>They don't allow you to specify what Map implementation is used</li> <li>They only create immutable maps</li> <li>They don't create an anonymous subclass of Map</li> </ul> <p>However, these differences shouldn't matter for many use cases, making this a good default approach for newer versions of Java.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload