如何返回在HashMap中作为值存储的数组

huangapple go评论72阅读模式
英文:

How do I return an array that's being stored as a value in a HashMap

问题

我正尝试将一个数组存储在哈希映射中,使得这个哈希映射也成为另一个哈希映射的子项。

为了以可视化方式表示我的意思:

parentHashMap <"myParentKey":childHashMap>
---childHashMap <"properties":myArray[]>
------myArray = ["value 1", "value 2", "etc"]

之所以使用这种看起来不太美观的存储方案,是因为我希望我的 childHashMap 对于 parentHashMap 中的每个键具有不同的 "properties" 值。

myArray 不一定会涵盖我试图存储的所有属性,而是可以容纳多个值的属性之一(例如 <"genresOfMusic": "rock, metal, jazz, country">)。

最终,我如何才能返回 myArray,以便我可以显示它的内容?此外,如果可以避免嵌套映射,对于更好的格式化存储方案的建议将不胜感激。

英文:

I am trying to store an array within a hashmap such that the hashmap is also the child of another hashmap.

To visually represent what I mean:

parentHashMap &lt;&quot;myParentKey&quot;:childHashMap&gt;
---childHashMap &lt;&quot;properties&quot;:myArray[]&gt;
------myArray = [&quot;value 1&quot;, &quot;value 2&quot;, &quot;etc&quot;]

The reason why I am making this eyesore of a storage solution is that I want my childHashMap to have different "properties" values for each key in parentHashMap.

myArray wouldn't necessarily be all the properties that I am trying to store, rather, it would be one property that can hold multiple values (i.e. <"genresOfMusic" : "rock, metal, jazz, country">)

Ultimately, how would I return myArray so that I can show its contents? Also, suggestions to better format my storage solution would be greatly appreciated instead of having nesting maps.

答案1

得分: 2

如果我理解你的问题正确,你在将一个String[]的实例放入了map中,那么:
你需要将其强制转换回这个类型。可以像这样进行操作:

HashMap<String, Object> properties = new HashMap<>();
Object array = properties.get("Key_To_Array");
if (array instanceof String[]) {
  String[] arrayElementsAsString = (String[]) array;
  // 对数组中的字符串做一些操作。
}
英文:

If I understand your question like you put a instance of String[] into the map, then:<br>
You have to cast it back to this type. Could be done like this:

HashMap&lt;String, Object&gt; properties = new HashMap&lt;&gt;();
Object array = properties.get(&quot;Key_To_Array&quot;);
if (array instanceof String[]) {
  String[] arrayElementsAsString = (String[]) array;
  // Do something with Strings in array.
}

答案2

得分: 0

你无法“解析”一个数组,只能解析字符串。

假设你确定键 hello 将映射到一个整数数组,那么:

int[] v = (int[]) properties.get("hello");
System.out.println("The second value is: " + v[1]);

如果你不确定,你可以始终这样做:

Object o = properties.get("hello");
if (o.getClass().isArray()) {
    // 如果 o 是一个数组,我们会进入这里。
    // (如果“hello”未映射,则会抛出 NullPointerException。)

    Object secondValue = java.lang.reflect.Array.get(o, 1);
}

总的来说,你的设计不好。在映射中进行异构存储听起来像是你非常非常糟糕地重新发明了类型化对象的概念。只需创建一个类,每个“属性”都有一个字段。如果这些数据来自于一些不是特别静态/名义类型的其他系统(比如一堆通过网络API传输的 JSON 数据),那么就应该使用处理这些数据的好工具。对于 JSON,你可以使用 jackson 或者 gson 等工具。

英文:

You can't 'parse' an array, you can only parse strings.

Let's say you know for sure that key hello will map to an int array, then:

int[] v = (int[]) properties.get(&quot;hello&quot;);
System.out.println(&quot;The second value is: &quot; + v[1]);

If you have no idea, you can always do:

Object o = properties.get(&quot;hello&quot;);
if (o.getClass().isArray()) {
    // we get here if o is an array.
    // (and a NullPointerException if &#39;hello&#39; is unmapped.

    Object secondValue = java.lang.reflect.Array.get(o, 1);
}

In general your design is bad, though. heterogenerous storage in a map sounds like you very very badly reinvented the concept of a typed object. Just make a class, with a field for each 'property'. If this data is coming from some other system that is not particularly statically/nominally typed (such as, say, a bunch of JSON via a web API) then use tools that are good at dealing with it. For JSON, you'd use jackson or gson, for example.

答案3

得分: 0

public static void main(String... args) {
    Map<String, Object> properties = new HashMap<>();
    properties.put("one", new int[] { 1, 2, 3 });
    properties.put("two", new String[] { "4", "5", "6" });

    properties.forEach((key, val) -> {
        if (val == null)
            System.out.format("key: %s is null\n", key);
        else if (val.getClass().isArray()) {
            String[] arr = new String[Array.getLength(val)];

            for (int i = 0; i < arr.length; i++)
                arr[i] = String.valueOf(Array.get(val, i));

            System.out.format("key: %s is an array: %s\n", key, Arrays.toString(arr));
        } else
            System.out.format("key: %s is not an array: %s\n", key, val);
    });
}
英文:
public static void main(String... args) {
    Map&lt;String, Object&gt; properties = new HashMap&lt;&gt;();
    properties.put(&quot;one&quot;, new int[] { 1, 2, 3 });
    properties.put(&quot;two&quot;, new String[] { &quot;4&quot;, &quot;5&quot;, &quot;6&quot; });

    properties.forEach((key, val) -&gt; {
        if (val == null)
            System.out.format(&quot;key: %s is null\n&quot;, key);
        else if (val.getClass().isArray()) {
            String[] arr = new String[Array.getLength(val)];

            for (int i = 0; i &lt; arr.length; i++)
                arr[i] = String.valueOf(Array.get(val, i));

            System.out.format(&quot;key: %s is an array: %s\n&quot;, key, Arrays.toString(arr));
        } else
            System.out.format(&quot;key: %s is not an array: %s\n&quot;, key, val);
    });
}

huangapple
  • 本文由 发表于 2020年10月27日 04:43:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/64544704.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定