Initialize Map in Java 9

In this post, we will discuss various methods to initialize map in Java 9.

 
Java 9 made it very convenient to create instances of map by providing static factory methods on the Map interface that creates compact, unmodifiable instance of Map. For example,

This supports maps upto 10 key-value pairs. There is a no var-args overload of Map.of() which can handle any number of mappings. To create a map with an arbitrary number of entries, we can use

It include varargs overloads, so there is no fixed limit on the map size. This approach requires each key-value pair to be boxed. For boxing keys and values, we can use

 
Here’s complete usage of this method:

 
As per Javadoc, the Map instances created by the Map.of() and Map.ofEntries() methods have the following characteristics:

  1. They are structurally immutable. Keys and values cannot be added, removed, or updated. Calling any mutator method will always cause UnsupportedOperationException to be thrown. However, if the contained keys or values are themselves mutable, this may cause the Map to behave inconsistently or its contents to appear to change.
     
  2. They disallow null keys and values. Attempts to create them with null keys or values result in NullPointerException.
     
  3. They are serializable if all keys and values are serializable.
     
  4. They reject duplicate keys at creation time. Duplicate keys passed to a static factory method result in IllegalArgumentException.
     
  5. The iteration order of mappings is unspecified and is subject to change.
     
  6. They are value-based. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones. Therefore, identity-sensitive operations on these instances (reference equality (==), identity hash code, and synchronization) are unreliable and should be avoided.
     

If we need a Map that can grow, we can use –

 
Please note that static factory methods on concrete collection classes such as HashMap are not included in Java 9. Since static methods on interfaces are not inherited, it will not be possible to invoke them via an implementing class, nor via an instance of the interface type.

 
Suggested Read: Initialize Map in Java

 
References: JEP 269: Convenience Factory Methods for Collections

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz