有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中遍历hashmaps的hashmap以检索字符串值

我是Java新手(对强类型不太熟悉),我有一个接受HashMap的方法。这个hashmap中的一个键包含一个键,该键的值有一个hashmap,它还指向一个hashmap,等等,直到我们到达一个字符串:y

HashMap1->HashMap2->HashMap3->HashMap4->String

我尝试按如下方式访问它:

HashMap1
    .get("aKey")
    .get("anotherKey")
    .get("yetAnotherKey")
    .get("MyString");

但后来我犯了个错误

Object does not have a method "get(String)

以下是简化的方法:

public HashMap<String, HashMap> getMyString(Map<String, HashMap> hashMap1) {
    String myString = hashMap1
                          .get("aKey")
                          .get("anotherKey")
                          .get("yetAnotherKey")
                          .get("MyString");

    // do something with myString.

    return hashMap1;
}

如何正确定义方法和参数以轻松访问嵌套元素

谢谢,


共 (3) 个答案

  1. # 1 楼答案

    首先应该使用接口而不是实现,因此尽可能使用Map(而不是HashMap)

    其次,您应该修复泛型并使用所有级别。现在,编译器可以帮助您并可能显示您的错误

    // i suppose you want to return a String, at least the method name tells it
    public String getMyString(Map<String, Map<String, Map<String, Map<String, String>>>> hashMap1) {
        String myString = hashMap1
                          .get("aKey")
                          .get("anotherKey")
                          .get("yetAnotherKey")
                          .get("MyString");
    
        return myString;
    }
    

    但我建议您使用不同的数据结构

  2. # 2 楼答案

    就这么简单

    HashMap1.get("aKey")   > return hashMap2
    .get("anotherKey")  > return hashMap3
    .get("yetAnotherKey")  > return hashMap4
    .get("MyString");  > return String
    

    添加部分有问题

    现在你有了如下的结构

    hashmap1  > hashmap2  > String 
    
    String myString = hashMap1.get("aKey").get("MyString");
    

    应该是这样的

  3. # 3 楼答案

    你打了太多的.get电话。也许最后一个是不需要的

    你能用任意数量的字符串字段创建class CompoundKey并将其用作键吗?这将简化您的设计

    要在Java中正确使用它,需要重写hashCodeequals方法