java - Hashmap 搜索中的 Hashmap
问题描述
Map<Integer, HashMap<String, Integer>> map = new HashMap<Integer,
HashMap<String, Integer>>();
map.put(1, new HashMap<>());
map.get(1).put("123",5);
map.get(1).put("124",3);
// i store (id, isbn, rate) in Hashmap in Hashmap
map.put(2, new HashMap<>());
map.get(2).put("123",5);
map.get(2).put("122",2);
我如何从 isbn 获取 id?
示例我想获取阅读 isbn 123 的用户的 ID?谢谢。
解决方案
您需要逐步思考:
- 迭代第一级 Map 的对
- 对于每一个,迭代它的对(第二级地图)
- 如果你找到一对好的
isbn
然后保存 1-lvl 地图的 ID
您可以如下构建一个方法,并像这样调用
List<Integer> listId = getIdFromIsbn("123", map);
static List<Integer> getIdFromIsbn(String isbn, Map<Integer, Map<String, Integer>> map) {
List<Integer> list = new ArrayList<>();
for (Map.Entry<Integer, Map<String, Integer>> entry : map.entrySet()) {
Map<String, Integer> value = entry.getValue();
for (Map.Entry<String, Integer> subEntry : value.entrySet()) {
if (subEntry.getKey().equals(isbn)) {
list.add(entry.getKey());
}
}
}
return list;
}
使用Stream
和 lambdas,它看起来像:
static List<Integer> getIdFromIsbn(String isbn, Map<Integer, Map<String, Integer>> map) {
return map.entrySet() // Set<Entry<Integer,Map<String,Integer>>>
.stream() // Stream<Entry<Integer,Map<String,Integer>>>
.flatMap(entry -> entry.getValue().entrySet() // Set<Entry<String,Integer>>
.stream() // Stream<Entry<String,Integer>>
.map(Map.Entry::getKey) // Stream<String>
.filter(isbn::equals) // Stream<String>
.map(subEntry -> entry.getKey())) // Stream<Integer>
.collect(Collectors.toList()); // List<Integer>
}
推荐阅读
- javascript - 将鼠标移到元素上的 DOM 方法是什么?
- debian - Postfix Error 451 4.3.5 服务器配置错误;服务器迁移后
- django - 当我使用 NON-gmail smtp 服务器通过 django 发送电子邮件时,我得到了 Google SMTPAuthenticationError,即使我不使用 smtp.gmail.com
- php - 使用php从数据库中获取多维数组时出错
- javascript - 如何在javascript中扁平化对象值
- javascript - React-Router open 新选项卡内容中的链接正在同一个现有选项卡中打开
- python - python通过递归函数获取所有子集
- phpstorm - 如何在 PhpStorm 中设置默认 PHP 版本/解释器?
- arrays - 是否可以在 2 个 for 循环中存储数据
- kotlin - Kotlin 空检查 !! 不短路评价?