Details Explanation of java.util.Map Collection enhancement in Java 9

The Map.of() and Map.ofEntries() static factory methods provide a convenient way to create immutable maps. The Map instances created by these methods have the following characteristics:

  • 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.
  • They disallow null keys and values. Attempts to create them with null keys or values result in NullPointerException.
  • They are serializable if all keys and values are serializable.
  • They reject duplicate keys at creation time. Duplicate keys passed to a static factory method result in IllegalArgumentException.
  • The iteration order of mappings is unspecified and is subject to change.
  • 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.
  • They are serialized as specified on the Serialized Form page.

Example:

public class HashMapDemo{
  public static void main(String ... args){
    java.util.Map<String,String> employeeDetails = java.util.Map.of("EmployeeName", "Subhash","EmployeeRole","JavaDeveloper");
    System.out.println("EmployeeName: "+employeeDetails.get("EmployeeName"));
    System.out.println("EmployeeRole: "+employeeDetails.get("EmployeeRole"));	
  }
}

 

Was this post helpful?

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *