繁体   English   中英

Hashmap 搜索中的 Hashmap

[英]Hashmap in Hashmap Search

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 Map 的 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>
}

您可以直接迭代地图:

List<Integer> idsFound = new ArrayList<>(); 
map.forEach((id, innerMap) -> innerMap.forEach((isbn, rate) -> {
    if (isbn.equals(isbnToMatch)) idsFound.add(id);
}));

迭代第一级地图,然后迭代嵌套地图以执行检查。

以下代码部分打印给定targetIsbn所有id

    for (Entry<Integer, HashMap<String, Integer>> entry : map.entrySet()) {
        int id = entry.getKey();
        Map<String, Integer> value = entry.getValue();

        for (Entry<String, Integer> subEntry : value.entrySet()) {
            String isbn = subEntry.getKey();
            int rate = subEntry.getValue();
            if (isbn.equals(targetIsbn))
                System.out.println("given isbn found for id " + id);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM