[英]How to union correctly Hashmap<String, ArrayList<Object>> and HashMap<String, Object>
I want to make my code clean add have the following trouble. 我想让我的代码干净添加有以下麻烦。 I want add
我想加
HashMap<String,Object> currentItem;
to my storage 到我的存储
HashMap<String, ArrayList<Object>> storage;
by the following way: 通过以下方式:
Add all Object
of currentItem
to ArrayList<Object>
of storage
according to the keys (they all are the same). 根据键将所有
currentItem
Object
添加到storage
ArrayList<Object>
(它们都是相同的)。
This is my variant how to add currentItem to storage according to the keys 这是我的变种如何根据键将currentItem添加到存储
if (storage.containsKey("article_link"))
{Object tmpObj;
ArayList<Object> listTemp;
tmpObj = currentItem.get("article_link");
listTemp = storage.get("article_link");
listTemp.add(tmpObj);
storage.put("article_link", listTemp);
tmpObj = o.get("image");
listTemp = storage.get("image");
listTemp.add(tmp);
storage.put("image", rrr);
}
and this for each hashmap key. 这对每个hashmap键都有用。 I can write special function for repeating code, but I hope it can be solved more easier.
我可以编写重复代码的特殊功能,但我希望它可以更容易地解决。
Thanks. 谢谢。
One thing to note here is that, you don't need to put the mapping for new arraylist again, once you modify it. 这里需要注意的一点是,一旦修改它,就不需要再次为新的arraylist设置映射。 The changes will be reflected in the
Map
automatically, since, what you are having is the reference to the actual ArrayList
object. 这些更改将自动反映在
Map
,因为您所拥有的是对实际ArrayList
对象的引用。
Secondly, you don't need to do all that hard-coding
. 其次,您不需要进行所有
hard-coding
。 You can simply iterate over your currentItem
map, and for each key-value
pair, check the existence of key
in storage
, and if found, just update the corresponding List
. 您可以简单地遍历
currentItem
映射,并为每个key-value
对检查storage
是否存在key
,如果找到,只需更新相应的List
。
Here's how you do that: - 这是你如何做到的: -
for (Entry<String, Object> entry: currentItem.entrySet()) {
if (storage.containsKey(entry.getKey()) {
storage.get(entry.getKey()).add(entry.getValue());
} else {
List<Object> newEntry = new ArrayList<Object>();
newEntry.add(entry.getValue());
storage.put(entry.getKey(), newEntry);
}
}
for (Entry<String, Object> entry: currentItem.entrySet()) {
if (!storage.containsKey(entry.getKey()) {
storage.put(new ArrayList<Object>());
}
storage.get(entry.getKey()).put(entry.getValue());
}
Set<Entry<String,Object> entries = currentItem.entrySet();
Iterator<Entry<String,Object>> i = entries.iterator();
while(i.hasNext()) {
Entry<String,Object> e = i.next();
if(storage.containsKey(e.getKey()) {
storage.get(e.getKey()).add(e.getValue());
}
else {
ArrayList l = new ArrayList();
l.add(e.getValue());
storage.put(e.getKey(),l);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.