-4

In Swift I can write a dictionary like this:

let myDict = [
    [
        "title": "some title",
        "val": "some val",
        "url": "some url"
    ],
[
        "title": "some title",
        "val": "some val",
        "url": "some url"
    ],
]

Is there a android Java version of that?

Kiow
  • 790
  • 2
  • 10
  • 31

3 Answers3

1

Java does not have dictionary or array literals. Instead we have interfaces, java.util.Map and java.util.List in the Collections API. These have several implementations including java.util.HashMap and java.util.ArrayList. You can combine these in any way you want. Creating a list of maps can unfortunately become quite verbose since you have to call the appropriate methods to add elements to these data structures. I suggest that you read about the Collections API to learn about all of the data structures that are available in Java.

Code-Apprentice
  • 69,701
  • 17
  • 115
  • 226
1

Import utility:

import java.util.HashMap;

And then you can use Map. The first line declares an empty variable with the type of HashMap and the two next lines add data into it.

Map vehicles = new HashMap();
vehicles.put("BMW", 5);
vehicles.put("Mercedes", 3);

As @Code-Apprentice mentioned. You need to import the required utility.

Maihan Nijat
  • 7,755
  • 6
  • 40
  • 87
0

There is no literal Dictionary in Java, the combination you're looking for is a List<Map<String, String>> Both List and Map are interfaces, so they can't be directly instantiated. In your case, the concrete classes for those are varied, but either ArrayList or LinkedList for List and HashMap for Map.

You can get something vaguely similar with anonymous classes:

List<Map<String, String>> myDict = new ArrayList<Map<String, String>>() {{
    add(new HashMap<String, String>() {{
        put("title", "some title");
    }});
}}
David Berry
  • 39,492
  • 12
  • 80
  • 91