Initialize a static map in Java with Examples

In this article, a static map is created and initialised in Java.

A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class.

  • Method 1:
    1. Creating a static map variable.
    2. Instantiating it in a static block.

    Below is the implementation of the above approach:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program to create a static map
      
    import java.util.*;
      
    class GFG {
      
        // Declaring the static map
        private static Map<Integer, String> map;
      
        // Instantiating the static map
        static
        {
            map = new HashMap<>();
            map.put(1, "GFG");
            map.put(2, "Geek");
            map.put(3, "GeeksForGeeks");
        }
      
        // Driver code
        public static void main(String[] args)
        {
            System.out.println(map);
        }
    }

    chevron_right

    
    

    Output:

    {1=GFG, 2=Geek, 3=GeeksForGeeks}
    
  • Method 2: Creating a static map variable and instantiating it together.

    Below is the implementation of the above approach:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program to create a static map
      
    import java.util.*;
      
    class GFG {
      
        // Declaring the static map
        private static Map<Integer, String> map
            = new HashMap<>() {
                  map.put(1, "GFG");
                  map.put(2, "Geek");
                  map.put(3, "GeeksForGeeks");
              }
      
        // Driver code
        public static void main(String[] args)
        {
            System.out.println(map);
        }
    }

    chevron_right

    
    

    Output:

    {1=GFG, 2=Geek, 3=GeeksForGeeks}
    

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.