Java 创建数组的列表
我想创建一个列表,每行包含一个数组,如下所示:Java 创建数组的列表,java,android,Java,Android,我想创建一个列表,每行包含一个数组,如下所示: key1 ->value1 key2 ->value2 key3 ->value3 键和值是字符串 如何执行此操作?如果您的密钥必须是字符串,则您希望使用映射而不是数组。你想要/需要一份清单 下面是一个例子: //declaring and initializing the list of maps //line below works for Java 7 //List<Map<String, String&g
key1 ->value1
key2 ->value2
key3 ->value3
键和值是字符串
如何执行此操作?如果您的密钥必须是字符串,则您希望使用映射而不是数组。你想要/需要一份清单
下面是一个例子:
//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("--------------------------");
}
你可以使用
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)
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);