Initializing a static Map using Stream in Java

Before initializing a static map using Stream in Java, we need to know what is static. static is a non-access modifier in Java used as blocks, variables, methods and nested classes. Hence, in order to create a static member(block, variable, method, nested class), we precede the declaration of blocks, variables, methods and nested classes with the ‘static’ keyword. Besides this, we know that using a static member, we can access it before any objects of its class made.

How to initialize a static Map using Stream in Java

Below is described process of initializing a static map using Stream in Java.

Static Map in Java:

A static map is a map that is declared to be as static, ie, we have it as a class member and hence can use it with class in Java.

Stream In Java:

A stream is a sequence of objects that supports methods by processing collections of objects in Java.

Procedure:

Following is the procedure we follow as to how to initialize a static map using Stream in Java

  1. We create a stream and insert the 2-dimensional values as Key-Value pairs in that stream. These Key-Value pairs values are used to instantiate the Map.
  2. Next, we use the collect() method of Stream so as to map the values from the stream to the map, ie, Collectors.toMap() method, the keyMapper and the ValueMapper.

Sample Code:

import java.util.*; 
import java.util.stream.Collectors;  

class staticMapJava { 

    private static Map<String, String> myMap  = Arrays.stream(new String[][] { 
            { "a", "Welcome" }, 
            { "b", "To" }, 
            { "c", "CodeSpeedy!" },
            { "d", "Happy" }, 
            { "e", "Learning!" } }) 
              .collect(Collectors.toMap(keyMapper -> keyMapper[0], valueMapper -> valueMapper[1])); 
 
    public static void main(String[] args) 
    { 
        System.out.println(myMap); 
    } 
}

Output:

{a=Welcome, b=To, c=CodeSpeedy!, d=Happy, e=Learning!}

Know More: map() in Python  Stream in Java

Leave a Reply

Your email address will not be published. Required fields are marked *