java - 如何实现像HashMap这样的多值hashmap> 在 Java 中
问题描述
我希望外部映射具有重复键,因此不能使用传统的哈希映射。
我想实现以下目标:
键值
Col--->apple-->Apple
Col--->ball--->Ball
Col1--->tree--->Tree
所以地图看起来像,
关键。值
Col-->[apple-->Apple],[ball-->Ball]
Col1-->[tree--->Tree]
请帮忙!
解决方案
在现代 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 来保持顺序。
推荐阅读
- python-2.7 - 如何从存储的 excel 行调用并仅返回没有坐标的值?
- kubernetes - 谷歌 Kubernetes 引擎和 VPN
- javascript - 如何在外部脚本中动态加载 jquery 和 jquery-ui
- r - 如何提高 R 中循环的处理时间,手动 xgboost 预测
- javascript - 如何在我的 Quill 项目中添加字符计数器?
- javascript - 如果我将鼠标移出或单击右箭头滑块不起作用,则单击左箭头后 JavaScript 上的滑块
- ios - 在动画中更改后文本消失
- java - 如何获取 WebContent/WEB-INF/classes 目录的路径
- python - 打开图片需要哪些包?
- assembly - 为什么序列化这个程序(CVE-2018-8120 概念证明)会导致它工作?