首页 > 解决方案 > 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?谢谢。

标签: javahashmap

解决方案


您需要逐步思考:

  • 迭代第一级 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>
}

推荐阅读