In this article, a static map is created and initialized 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:
- Creating a static map variable.
- Instantiating it in a static block.
Below is the implementation of the above approach:
// 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);
   Â
}
}
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:
// 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);
   Â
}
}
Output:{1=GFG, 2=Geek, 3=GeeksForGeeks}