[java] How do I insert values into a Map<K, V>?

I am trying to create a map of strings to strings. Below is what I've tried but neither method works. What's wrong with it?

public class Data
{
    private final Map<String, String> data = new HashMap<>();
    data["John"] = "Taxi Driver";
    data.put("John", "Taxi Driver");
}

This question is related to java

The answer is


The syntax is

data.put("John","Taxi driver");

The two errors you have in your code are very different.

The first problem is that you're initializing and populating your Map in the body of the class without a statement. You can either have a static Map and a static {//TODO manipulate Map} statement in the body of the class, or initialize and populate the Map in a method or in the class' constructor.

The second problem is that you cannot treat a Map syntactically like an array, so the statement data["John"] = "Taxi Driver"; should be replaced by data.put("John", "Taxi Driver"). If you already have a "John" key in your HashMap, its value will be replaced with "Taxi Driver".


Try this code

HashMap<String, String> map = new HashMap<String, String>();
map.put("EmpID", EmpID);
map.put("UnChecked", "1");