Initialize Map Java

Java 8 and lower Versions:

Map<String, String> myMap = createNewMap();
 
private static Map<String, String> createNewMap() {
    Map<String,String> tempMap = new HashMap<String,String>();
    tempMap .put("a", "Susan");
    tempMap .put("b", "Roy");
    return tempMap;
}

Immutable Map in Java 9 and higher Versions:

// It works with the limit of 10 elements
Map<String, String> test1 = Map.of(
    "a", "Roxy",
    "b", "Sue"
);
 
//It works with no limit or for any number of elements
import static java.util.Map.entry;    
Map<String, String> test2 = Map.ofEntries(
    entry("a", "Jai"),
    entry("b", "Sandy")
);

Mutable Map in Java 9 and higher Versions:

// It works with the limit of 10 elements
Map<String, String> test1 = new HashMap<>(Map.of(
    "a", "Roxy",
    "b", "Sue"
));
 
//It works with no limit or for any number of elements
import static java.util.Map.entry;    
Map<String, String> test2 = new HashMap<>(Map.ofEntries(
    entry("a", "Jai"),
    entry("b", "Sandy")
));
Please follow and like us:
Content Protection by DMCA.com