简体   繁体   English

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

[英]Walking a hashmap of hashmaps to retrieve a string value in Java

I'm new to Java (and not too comfortable with strong typing) and I have a method that takes in a HashMap. 我是Java的新手(对于强类型不太熟悉)我有一个接受HashMap的方法。 A key in this hashmap contains a key, which has a hashmap for value, which also points to a hashmap, etc, until we reach a string:y 这个hashmap中的一个键包含一个键,它有一个值的hashmap,它也指向一个hashmap等,直到我们到达一个字符串:y

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

I am trying to access it as follows: 我试图访问它如下:

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

But then I get an error, 但后来我得到一个错误,

Object does not have a method "get(String) 对象没有方法“get(String)

Here is the method, simplified: 这是方法,简化:

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;
}

How would someone properly define the method and the parameters to access nested elements easily? 如何正确定义方法和参数以轻松访问嵌套元素?

Thank you, 谢谢,

You made too many .get calls. 你做了太多.get电话。 Probably the last one is not needed. 可能最后一个不需要。

Can you just create class CompoundKey with arbitrary number of String fields and use it as a key? 您可以使用任意数量的String字段创建class CompoundKey并将其用作键吗? It would simplify your design. 它会简化您的设计。

To use it properly in Java you need to override hashCode and equals methods. 要在Java中正确使用它,您需要覆盖hashCodeequals方法。

Simple as that 就那么简单

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

There is something wrong with the adding part. 添加部分有问题。

Now you have structure like below. 现在你有如下结构。

hashmap1 --> hashmap2 --> String 

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

That is how it should be. 应该是这样的。

You should first of all use interfaces not implementation, therefore use Map (and not HashMap) where possible. 首先应该使用接口而不是实现,因此尽可能使用Map (而不是HashMap)。

And second, you should repair your Generics and use all levels. 其次,你应该修复你的泛型并使用所有级别。 Now the compiler can help you and possible show your error. 现在,编译器可以帮助您并可能显示您的错误。

// 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;
}

Yet i suggest that you use a different data structure. 但我建议你使用不同的数据结构。

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

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