Wednesday, July 3, 2024
HomeLanguagesJavaInitialize a static Map using Stream in Java

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 objects that supports various methods which can be pipelined to produce the desired result.

Approach:

  • Create a stream and insert 2D values as Key and Value pair in it.
  • These values will be later used to instantiate the Map.
  • Using the collect() method of Stream, map the values from the stream to the map.
  • This can be done with the help of Collectors.toMap() method and the keyMapper and ValueMapper respectively.

Below is the implementation of the above approach:




// Java program to create a static map using Stream
  
import java.util.*;
import java.util.stream.Collectors;
  
class GFG {
  
    // Declaring and instantiating the static map
    private static Map<String, String> map
        = Arrays.stream(new String[][] {
                            { "1", "GFG" },
                            { "2", "Geek" },
                            { "3", "GeeksForGeeks" } })
              .collect(Collectors.toMap(
                  keyMapper -> keyMapper[0], valueMapper -> valueMapper[1]));
  
    // Driver code
    public static void main(String[] args)
    {
        System.out.println(map);
    }
}


Output:

{1=GFG, 2=Geek, 3=GeeksForGeeks}
Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments