How to Populate Predefined Static Data in HashMap (Map) in Java?

Posted in /  

How to Populate Predefined Static Data in HashMap (Map) in Java?

Ramya Shankar
Last updated on June 16, 2024

    A map is used to store key-value pairs. For example, {“name”, “john”} is a key-value pair, where name is the key, and ‘john’ is the value. It is easy to populate static data in a HashMap.

    In this article, we will discuss how to populate predefined static data in HashMap in Java. We will do this by implementing a HashMap in Java to initialize or populate a static HashMap.

    How to Populate Predefined Static Data in HashMap (Map) in Java?

    In Java 9, we can populate predefined static data in HashMap with just one line, using the Map.of() method.

    Map<String, String> details = Map.of(
    "Name", "John",
    "Age", "30"

    We can also specify the type of Map, which, in our case, is a HashMap:

    Map<String, String> details = new HashMap<String, String>(Map.of(
    "Name", "John",
    "Age", "30"

    Before Java 9, things were different. To populate HashMap in previous Java versions, we have to use the put() method.

    Map<String, String> detailsMap = new HashMap<String, String>();
    detailsMap.put("Name", "John");
    detailsMap.put("Age", "30");
    detailsMap.put("Grade", "A");

    As we can see, put can be used to statically populate a map. Note that first we create an empty map and then populate it. Here is another example to show a data type other than the String datatype:

    Map<Character, Integer> gradeMap = new HashMap<Character, Integer>();
    gradeMap.put('A', 90);
    gradeMap.put('B', 70);
    gradeMap.put('C', 55);
    The output will be:
    {A=90, C=55, B=70}

    Note that we cannot use primitive types. That is why we have used Character object and Integer object in place of char and int. Another way to populate a static HashMap is to use an anonymous class:

    Map<Character, Integer> details = new HashMap<Character, Integer>() {
    put('A', 90);
    put('B', 70);
    put('C', 55);
    System.out.println("Anonymous class map: " + details);

    You can also make a map immutable once you populate the static HashMap.

    Map<String,String> mutableMap = new HashMap<String, String>();
    mutableMap.put("Name", "John");
    mutableMap.put("Age", "30");
    mutableMap.put("Grade", "A");
    Map<String,String> immutableMap = Collections.unmodifiableMap(mutableMap);

    If we try to modify the immutable Map, we will get java.lang.UnsupportedOperationException .


    We have explored the various ways to populate static HashMap in Java. Moreover, we also discussed the difference between mutable and immutable maps and whether they can be populated or not.

    People are also reading:

    Leave a Comment on this Post