Initialize Static Map Java

Method 1:

import java.util.HashMap;
import java.util.Map;
 
public class Test {
    private static final Map<Integer, String> tempMap = new HashMap<>();
    static {
        tempMap.put(1, "Sandy");
        tempMap.put(2, "Roxy");
    }
}

Method 2:

import java.util.HashMap;
import java.util.Map;
 
public class Test {
    private static final Map<Integer, String> tempMap = new HashMap<>(){
        {
            put(1, "Susan");
            put(2, "Sue");
        }
    };
}

Method 3:

import java.util.HashMap;
import java.util.Map;
 
public class Test {
    private static final Map<Integer, String> tempMap;
    static {
        Map<Integer, String> aMap = new HashMap<>();
        aMap.put(1, "Roxy");
        aMap.put(2, "Sandy");
        tempMap = Collections.unmodifiableMap(aMap);
    }
}
Please follow and like us:
Content Protection by DMCA.com