转换Map< String,String>映射到< String,Object> [英] Converting Map<String,String> to Map<String,Object>
问题描述
我有两张地图
Map<String, String> filterMap
Map<String, Object> filterMapObj
我需要的是将Map<String, String>
转换为Map<String, Object>
的方法.
我在这里使用代码
What I need is I would like to convert that Map<String, String>
to Map<String, Object>
.
Here I am using the code
if (filterMap != null) {
for (Entry<String, String> entry : filterMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
Object objectVal = (Object)value;
filterMapObj.put(key, objectVal);
}
}
它工作正常,是否有其他方法可以执行此操作而无需遍历Map中的所有条目.
It works fine, Is there any other ways by which I can do this without iterating through all the entries in the Map.
推荐答案
您可以只使用putAll
:
filterMapObj.putAll(filterMap);
(请参见 Javadoc .)
编辑后添加:我应该注意,上述方法或多或少等效于迭代地图元素:它将使您的代码更整洁,但是如果您不想这样做的原因遍历元素实际上是一个性能问题(例如,如果您的地图很大),那么它可能不会帮助您.另一种可能性是写:
Edited to add: I should note that the above method is more-or-less equivalent to iterating over the map's elements: it will make your code cleaner, but if your reason for not wanting to iterate over the elements is actually a performance concern (e.g., if your map is enormous), then it's not likely to help you. Another possibility is to write:
filterMapObj = Collections.<String, Object>unmodifiableMap(filterMap);
创建filterMap
的不可修改的视图".当然,这更具限制性,因为它不允许您单独修改filterMapObj
和filterMap
. (不能修改filterMapObj
,对filterMap
的任何修改也会影响filterMapObj
.)
which creates an unmodifiable "view" of filterMap
. That's more restrictive, of course, in that it won't let you modify filterMapObj
and filterMap
independently. (filterMapObj
can't be modified, and any modifications to filterMap
will affect filterMapObj
as well.)
这篇关于转换Map< String,String>映射到< String,Object>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!