首先你要理解 Map的基本结构,key-value
这里最外层的Map,key是String类型,value是ArrayList。ArrayList里面放得又是Map,这个Map的key是String,value也是String。
import java.util.ArrayListimport java.util.HashMap
import java.util.Map
public class Test {
public static void main(String[] args) {
Map<String, ArrayList<Map<String, String>>> topMap = new HashMap<>()
String key1 = "map_key1" // topMap 的第一个key
ArrayList<Map<String, String>> value1 = new ArrayList<>() // topMap 的第一个value
// start
Map<String, String> strMap = new HashMap<>()
strMap.put("hello", "你好")
strMap.put("thanks", "谢谢")
value1.add(strMap)
value1.add(new HashMap<>()) // 添加一个空的 Map
// end
topMap.put(key1, value1) // 放入topMap
// 以上 start 到 end 段的代码是在往value1的ArrayList中填充数据
// 不填充也可以放入到topMap中,就像下面这样
topMap.put("emptyList", new ArrayList<Map<String, String>>())
topMap.put("emptyList2", new ArrayList<>()) // jdk 1.7 及之后推荐这样写,省掉泛型描述。前面的new HashMap<>()、new ArrayList<>()也是省掉了
}
}
HashMap 是一种常用的数据结构,一般用来做数据字典或者 Hash 查找的容器。普通青年一般会这么初始化:HashMap<String, String>map = new HashMap<String, String>()
map.put("name", "test")
map.put("age", "20")
看完这段代码,很多人都会觉得这么写太啰嗦了,文艺青年一般这么来了:
HashMap<String, String>map = new HashMap<String, String>() {
{
map.put("name", "test")
map.put("age", "20")
}
}