在现代 Java 中实现这一点的一个很好、紧凑的方法是:
Map<String, Map<String, String>> map = new HashMap<>();
map.computeIfAbsent("Col", k -> new HashMap<String,String>()).put("apple", "Apple");
map.computeIfAbsent("Col", k -> new HashMap<String,String>()).put("ball", "Ball");
map.computeIfAbsent("Col", k -> new HashMap<String,String>()).put("tree", "Tree");
有点冗长,但我假设你实际上会在这个例子中这样做:
String[][] values = {
{"Col", "apple", "Apple"},
{"Col", "ball", "Ball"},
{"Col1", "tree", "Tree"},
};
Map<String, Map<String, String>> map = new LinkedHashMap<>();
for (String[] row : values) {
map.computeIfAbsent(row[0], k -> new LinkedHashMap<String, String>()).put(row[1], row[2]);
}
注意:我使用 LinkedHashMap 来保持顺序。