In Java, you can create a list of dictionaries using the `ArrayList` class for the outer list and `HashMap` class for the inner dictionaries.
In this example,
dict1
and dict2
using the HashMap
class.listOfDicts
using the ArrayList
class and initialize it with the inner dictionaries.import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, String> dict1 = new HashMap<>();
dict1.put("key1", "value1");
dict1.put("key2", "value2");
Map<String, String> dict2 = new HashMap<>();
dict2.put("key3", "value3");
dict2.put("key4", "value4");
List<Map<String, String>> listOfDicts = new ArrayList<>();
listOfDicts.add(dict1);
listOfDicts.add(dict2);
System.out.println(listOfDicts);
}
}
[{key1=value1, key2=value2}, {key3=value3, key4=value4}]
In this example,
listOfDictsEmpty
using the ArrayList
class.dict3
and dict4
using the HashMap
class.add
method to add the inner dictionaries dict3
and dict4
to the outer list listOfDictsEmpty
.import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
List<Map<String, String>> listOfDictsEmpty = new ArrayList<>();
Map<String, String> dict3 = new HashMap<>();
Map<String, String> dict4 = new HashMap<>();
listOfDictsEmpty.add(dict3);
listOfDictsEmpty.add(dict4);
System.out.println(listOfDictsEmpty);
}
}
[{}, {}]
In this tutorial, we learned How to create a List of Dictionaries in Java language with well detailed examples.