The Wayback Machine - https://web.archive.org/web/20240906204611/https://www.geeksforgeeks.org/initialize-a-static-map-using-java-9-map-of/
Open In App

Initialize a static Map using Java 9 Map.of()

Last Updated : 14 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Static Map 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.

Java 9 feature – Map.of() method
In Java 9, Map.of() was introduced which is a convenient way to create instances of Map interface. It can hold up to 10 key-value pairs.

Approach:

  • Pass the map values as Key and Value pair in the Map.of() method.
  • A static factory Map instance is returned.
  • Store it in Map and use.

Below is the implementation of the above approach:

Example 1:




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


Output:

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

Example 2: To show the error when 10 key-value pairs are given




// Java program to create a static map using Java 9
  
import java.util.*;
  
class GFG {
  
    // Declaring and instantiating the static map
    private static Map<String, String> map
        = Map.of("1", "GFG",
                 "2", "Geek",
                 "3", "GeeksForGeeks",
                 "4", "G",
                 "5", "e",
                 "6", "e",
                 "7", "k",
                 "8", "s",
                 "9", "f",
                 "10", "o");
  
    // Driver code
    public static void main(String[] args)
    {
        System.out.println(map);
    }
}


Output:

{10=o, 9=f, 8=s, 7=k, 6=e, 5=e, 4=G, 3=GeeksForGeeks, 2=Geek, 1=GFG}

Example 3: To show the error when more than 10 key-value pairs are given




// Java program to create a static map using Java 9
  
import java.util.*;
  
class GFG {
  
    // Declaring and instantiating the static map
    private static Map<String, String> map
        = Map.of("1", "GFG",
                 "2", "Geek",
                 "3", "GeeksForGeeks",
                 "4", "G",
                 "5", "e",
                 "6", "e",
                 "7", "k",
                 "8", "s",
                 "9", "f",
                 "10", "o",
                 "11", "r");
  
    // Driver code
    public static void main(String[] args)
    {
        System.out.println(map);
    }
}


Compilation Error:

Main.java:12: error: no suitable method found for
 of(String, String,
    String, String,
    String, String,
    String, String,
    String, String,
    String, String,
    String, String,
    String, String,
    String, String,
    String, String,
    String, String)
        
1 error

Related Articles:



Similar Reads

Initialize a static Map using Stream in Java
In this article, a static map is created and initialized in Java using Stream. Static Map 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. Stream In Java Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of
2 min read
Initialize a static Map in Java using Double Brace Initialization
In this article, a static map is created and initialised in Java using Double Brace Initialization. Static Map 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. Double Brace Initialization In Double Brace Initialization: The first brace creates a new Anonymous
2 min read
Initialize a static map in Java with Examples
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 creat
1 min read
Class Loading and Static Blocks Execution Using Static Modifier in Java
Static is a keyword which when attached to the method, variable, Block makes it Class method, class variable, and class Block. You can call a static variable/method using ClassName. JVM executes the static block at “CLASS LOADING TIME” Execution Order: There is an order in which static block/method/variable gets initialized. Static BlockStatic Vari
3 min read
Understanding "static" in "public static void main" in Java
Following points explain what is "static" in the main() method: main() method: The main() method, in Java, is the entry point for the JVM(Java Virtual Machine) into the java program. JVM launches the java program by invoking the main() method. Static is a keyword. The role of adding static before any entity is to make that entity a class entity. It
3 min read
Difference between static and non-static method in Java
A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. Every method in java defaults to a non-static method without static keyword preceding it. Non-static methods can access any static method and static variable, without cr
6 min read
Difference between static and non-static variables in Java
There are three types of variables in Java: Local VariablesInstance VariablesStatic Variables The Local variables and Instance variables are together called Non-Static variables. Hence it can also be said that the Java variables can be divided into 2 categories: Static Variables: When a variable is declared as static, then a single copy of the vari
4 min read
Why non-static variable cannot be referenced from a static method in Java
Java is one of the most popular and widely used programming language and platform. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In java, methods can be declared as either static or non-static. In this article, let's discuss why non-static vari
4 min read
Difference Between Static and Non Static Nested Class in Java
Nested classes are divided into two categories namely static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes. A class can either be static or non-static in java. So there is a lot of difference between making a class static or non-static. There are two kind
4 min read
Static and non static blank final variables in Java
A variable provides us with named storage that our programs can manipulate. There are two types of data variables in a class: Instance variables : Instance variables are declared in a class, but outside a method, constructor or any block. When a space is allocated for an object in the heap, a slot for each instance variable value is created. Instan
5 min read
Understanding storage of static methods and static variables in Java
In every programming language, memory is a vital resource and is also scarce. Hence the memory must be managed thoroughly without any leaks. Allocation and deallocation of memory is a critical task and requires a lot of care and consideration. In this article, we will understand the storage of static methods and static variables in Java. Java Virtu
6 min read
Internal static variable vs. External static variable with Examples in C
The static variable may be internal or external depending on the place of declaration. Both kinds of static variables are stored in initialized data segments. Internal Static Variables Internal Static variables are defined as those having static variables which are declared inside a function and extend up to the end of the particular function. Synt
2 min read
Initialize a list in a single line with a specified value using Java Stream
Given a value N, the task is to create a List having this value N in a single line in Java using Stream. Examples: Input: N = 5 Output: [5] Input: N = GeeksForGeeks Output: [GeeksForGeeks] Approach: Get the value N Generate the Stream using generate() method Set the size of the List to be created as 1 using limit() method Pass the value to be mappe
2 min read
Initialize an ArrayList in Java
ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. ArrayList inherits AbstractList class and implements List interface.ArrayList is initialized by a size
3 min read
KeyPairGenerator initialize() method in Java with Examples
initialize(int keysize) The initialize() method of java.security.KeyPairGenerator is used to initialize KeyPairGenerator object for further use. Syntax: public void initialize(int keysize) Parameters: This method seeks keysize of int type as a parameter.Return Value: This method has nothing to return.Exception: This method throws InvalidParameterEx
3 min read
Different Ways To Declare And Initialize 2-D Array in Java
An array with more than one dimension is known as a multi-dimensional array. The most commonly used multi-dimensional arrays are 2-D and 3-D arrays. We can say that any higher dimensional array is basically an array of arrays. A very common example of a 2D Array is Chess Board. A chessboard is a grid containing 64 1x1 square boxes. You can similarl
8 min read
How to Initialize an Array in Java?
An array is a data structure in Java that is used to store data objects having the same data type. Each and every element in an array has a unique index value. In an array, we have to declare its size first and the size of the array is fixed. In an array, we can store elements of different data types like integer, string, date and etc. In this arti
5 min read
Initialize HashMap in Java
HashMap in Java is a part of the java.util package and allows storing key-value pairs. Initializing a HashMap can be done in multiple ways, including static blocks, utility methods from the Collections class, and modern approaches provided by Java 8 and Java 9. This article will guide you through these methods with clear examples and explanations.
4 min read
How to Initialize and Compare Strings in Java?
String is one of the most basic data types and it is widely used in storing and manipulating pieces of text. One of the fundamental features of strings in Java is their immutability that is once a string is created, it will never be changed. Immutability creates two general ways of initialization with strings in Java using the String Pool. This art
5 min read
How to Handle Static Web Tables using Selenium WebDriver using Java?
Web Tables are used to organize similar types of content on the web page, Web tables are groups of elements that are logically stored in a row and column format. Web table has various HTML tags like., table, th, tr, td. Let's understand these tags a bit more: &lt;table&gt; - It defines a table&lt;th&gt; - It defines a header cell&lt;tr&gt; - It def
3 min read
Using Static Variables in Java
Here we will discuss the static variables in java. Java actually doesn’t have the concept of Global variable. To define a Global variable in java, the keyword static is used. The advantage of the static variable is discussed below. Now geeks you must be wondering out what are the advantages of static variable, why to incorporate in our program. Now
3 min read
Java - Calling Non Static Members Directly From Constructor Without Using the Object Name
Java is an Object-Oriented Programming(OOP) language. We need to create objects in order to access methods and variables inside a class. However, this is not always true. While discussing static keywords in java, we learned that static members are class level and can be accessed directly without any instance. Here we will be discussing how we can a
3 min read
Initialize a list in a single line with a specified value
Given a value N, the task is to create a List having this value N in a single line in Java using Collection Framework only. Examples: Input: N = 5 Output: [5] Input: N = GeeksForGeeks Output: [GeeksForGeeks] Approach: Get the value N Generate a Collection with a single value N using Collections.nCopies() method Store this collection as a List. Belo
1 min read
Comparison of static keyword in C++ and Java
Static keyword is used for almost the same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java. Similarities between C++ and Java for Static KeywordStatic data members can be defined in both languages.Static member functions can be defined in both languages
6 min read
Can we Overload or Override static methods in java ?
Let us first define Overloading and Overriding. Overriding: Overriding is a feature of OOP languages like Java that is related to run-time polymorphism. A subclass (or derived class) provides a specific implementation of a method in the superclass (or base class). The implementation to be executed is decided at run-time and a decision is made accor
5 min read
Static Control Flow in Java
Static Control Flow decides the sequence of activities/steps that will be executed in order when we run a java class that contains static variables, methods, and blocks. This article will explain how static control flow occurs whenever a Java program is executed. Prerequisite: Static Blocks The Static Control Flow mechanism performs the following 3
4 min read
Static method in Interface in Java
Static Methods in Interface are those methods, which are defined in the interface with the keyword static. Unlike other methods in Interface, these static methods contain the complete definition of the function and since the definition is complete and the method is static, therefore these methods cannot be overridden or changed in the implementatio
2 min read
Static Block and main() method in Java
In Java static block is used to initialize the static data members. Important point to note is that static block is executed before the main method at the time of class loading. This is illustrated well in the following example: // Java program to demonstrate that static // block is executed before main() class staticExample { // static block stati
2 min read
Why can't static methods be abstract in Java?
In Java, a static method cannot be abstract. Doing so will cause compilation errors.Example: Java Code // Java program to demonstrate // abstract static method import java.io.*; // super-class A abstract class A { // abstract static method func // it has no body abstract static void func(); } // subclass class B class B extends A { // class B must
3 min read
Constructor Overloading with Static Block in Java
In Java, Constructor is a block of codes similar to the method that is used to initialize the object’s state. A constructor is invoked at the time of object or instance creation. Each time an object is created using a new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of
4 min read
Article Tags :
Practice Tags :