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"); }
The standard solution to add values to a map is using the put() method, which associates the specified value with the specified key in the map. Note that if the map already contains a mapping corresponding to the specified key, the old value will be replaced by the specified value.
You can use the Add Data button on the ArcMap toolbar to add data to your map. Click Add Data, browse to the data you want to add, then click Add. The data is added to the table of contents, but you'll still have to geocode the data's attribute table on the map to make it available for customer or store setup.
We can also initialize the map using the double-brace syntax: Map<String, String> doubleBraceMap = new HashMap<String, String>() {{ put("key1", "value1"); put("key2", "value2"); }};
Add and update entries To add a new key-value pair to a mutable map, use put() . When a new entry is put into a LinkedHashMap (the default map implementation), it is added so that it comes last when iterating the map. In sorted maps, the positions of new elements are defined by the order of their keys.
There are two issues here.
Firstly, you can't use the []
syntax like you may be able to in other languages. Square brackets only apply to arrays in Java, and so can only be used with integer indexes.
data.put
is correct but that is a statement and so must exist in a method block. Only field declarations can exist at the class level. Here is an example where everything is within the local scope of a method:
public class Data { public static void main(String[] args) { Map<String, String> data = new HashMap<String, String>(); data.put("John", "Taxi Driver"); data.put("Mark", "Professional Killer"); } }
If you want to initialize a map as a static field of a class then you can use Map.of
, since Java 9:
public class Data { private static final Map<String, String> DATA = Map.of("John", "Taxi Driver"); }
Before Java 9, you can use a static initializer block to accomplish the same thing:
public class Data { private static final Map<String, String> DATA = new HashMap<>(); static { DATA.put("John", "Taxi Driver"); } }
The syntax is
data.put("John","Taxi driver");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With