---
title: "How to Initialize a static Map?"  
description: "How to Initialize a static Map?"  
author: "Anonymous User"  
published: 2015-07-03  
updated: 2015-07-03  
canonical: https://www.mindstick.com/forum/23316/how-to-initialize-a-static-map  
category: "java"  
tags: ["java", "collection"]  
reading_time: 2 minutes  

---

# How to Initialize a static Map?

How would you initialise a [static](https://www.mindstick.com/articles/12098/the-static-keyword-the-static-methods) [Map](https://yourviews.mindstick.com/view/81351/nepal-parliament-s-approves-new-controversial-map-india-rejects-it-but) in [Java](https://www.mindstick.com/articles/12214/web-development-company-in-india-laid-on-the-foundation-of-concrete-java-programming)?\
[Method](https://www.mindstick.com/forum/166/webservice-method) one: Static initializer Method two: [instance](https://www.mindstick.com/forum/155658/testing-connection-to-cloud-sql-instance-with-a-mysql-client-from-vm-instance) initialiser ([anonymous](https://www.mindstick.com/interview/1140/what-is-anonymous-class-in-java) subclass) or some other method?\
What are the [pros and cons](https://www.mindstick.com/blog/11048/pros-and-cons-of-hadoop-system) of each?\
Here is an example illustrating two [methods](https://www.mindstick.com/articles/13060/runny-nose-remedy-methods-that-work-best):

```
import java.util.HashMap;import java.util.Map;public class Test {    private static final Map<Integer, String> myMap = new HashMap<Integer, String>();    static {        myMap.put(1, "one");        myMap.put(2, "two");    }    private static final Map<Integer, String> myMap2 = new HashMap<Integer, String>(){        {            put(1, "one");            put(2, "two");        }    };}
```

## Replies

### Reply by Anonymous User

The instance initialiser is just syntactic sugar in this case, right? I don't see why you need an extra anonymous class just to initialize. And it won't work if the class being created is final.\
You can create an immutable map using a static initialiser too:

```
public class Test {    private static final Map<Integer, String> myMap;    static {        Map<Integer, String> aMap = ....;        aMap.put(1, "one");        aMap.put(2, "two");        myMap = Collections.unmodifiableMap(aMap);    }}
```


---

Original Source: https://www.mindstick.com/forum/23316/how-to-initialize-a-static-map

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
