我想创建一个每一行包含如下数组的列表:
key1 ->value1
key2 ->value2
key3 ->value3
(键和值为字符串)
我怎么能这样做?
答案 0 :(得分:4)
如果您的密钥必须是String
,那么您希望使用Map
而不是数组。你想要/需要一个List<Map<String, String>>
。
以下是一个例子:
//declaring and initializing the list of maps
//line below works for Java 7
//List<Map<String, String>> listOfMaps = new ArrayList<>();
//if you want/need to use Java 6 then use the following
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
//declaring, initializing and filling a map
//line below works for Java 7
//Map<String, String> map1 = new HashMap<>();
//if you want/need to use Java 6 then use the following
Map<String, String> map1 = new HashMap<String, String>();
map1.put("name", "Luiggi");
map1.put("lastname", "Mendoza");
map1.put("maintag", "Java");
//declaring, initializing and filling another map
//line below works for Java 7
//Map<String, String> map2 = new HashMap<>();
//if you want/need to use Java 6 then use the following
Map<String, String> map2 = new HashMap<String, String>();
map2.put("name", "Foo");
map2.put("lastname", "Bar");
map2.put("maintag", "Scala"); //I have nothing against scala
//add maps into the list
listOfMaps.add(map1);
listOfMaps.add(map2);
//Show contents of the list and map
System.out.println(listOfMaps);
//Traverse each element of the List to access key and value
int index = 0;
//it is better to use Iterator or enhanced for each than using List#get(index)
for (Map<String, String> map : listOfMaps) {
System.out.println("Printing element " + index++);
for(Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println("--------------------------");
}
答案 1 :(得分:3)
您可以使用
ArrayList<Map<String, String>>()
这将具有以下结构
所以要设置一个键值对:
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map = new HashMap<String, String>();
map.put(key, value);
map.put(key1, value1);
list.add(map);
所以要从列表的第一个索引中的键中获取值:
String value = list.get(0).get(key)
答案 2 :(得分:3)
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "1");
map.put("key2", "2");
Map<String, String> anotherMap = new HashMap<String, String>();
anotherMap .put("key3", "3");
anotherMap .put("key4", "4");
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
listOfMaps.add(map);
listOfMaps.add(anotherMap);
为什么需要此列表?你需要做什么?或者这只是一个练习?