2

In swift I can declare a dictionary (key value pairs) like so

var toppings = [
        "Onions":"Red",
        "Peppers":"Green",
    ]

What is the equivalent (declare key value pairs) in Java?

I have tried modifying an array i.e. changing...

public String[] couplets = {
        "Onions",
        "Peppers",
};

...to...

 public String[] toppings = {
        "Onions":"Red",
        "Peppers":"Green",
};

...but it does not work.

I appreciate they are different languages so likely I am oversimplifying this by trying to do a straight like for like.

Essentially I would like to create a static list of key value pairs in Java.

I have googled for suggestions but all the answers seem overly complicated compared to what I can do in swift so I am wondering if there is a straightforward way - Perhaps there isn't...

Any advice is much appreciated

Thanks

Nick
  • 914
  • 1
  • 10
  • 30

3 Answers3

11

http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html

A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.

Map<String,String> toppings = new HashMap<>();
toppings.put("Onions","Red");
toppings.put("Peppers","Green");

Maps are great, you will end up using them a lot :)

Ken Wolf
  • 23,133
  • 6
  • 63
  • 84
  • Thanks Ken this is exactly what I was looking for, 1 question .put seems to be giving me an error - do I need to import something for this method to work? – Nick Mar 03 '15 at 20:18
  • You shouldn't need to import anything and `.put` shouldn't give you an error if you have defined `toppings` as above. Anyway, your IDE should tell you what the error is which should give you a clue to solving it. – Ken Wolf Mar 03 '15 at 20:23
0

Try the Map.

Instanciate new Map :

Map<String, String> map = new HashMap<String, String>();

Put values :

map.put("Onions","Red");

Read values :

map.get("Onions"); will return "Red"

Bubu
  • 1,533
  • 14
  • 14
0

If you need work with a String key you should use an HashMap as suggested in other answers.

If you can use an Integer key, I suggest you using a SparseArray

SparseArray<String> values = new SparseArray<String>();
values.put(1,"value1");
values.put(2,"value2");
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841