Java 将 Map<String,String> 转换为 Map<String,Object>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21037263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting Map<String,String> to Map<String,Object>
提问by arjuncc
I have Two Maps
我有两张地图
Map<String, String> filterMap
Map<String, Object> filterMapObj
What I need is I would like to convert that Map<String, String>
to Map<String, Object>
.
Here I am using the code
我需要的是我想将其转换Map<String, String>
为Map<String, Object>
. 我在这里使用代码
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);
}
}
It works fine, Is there any other ways by which I can do this without iterating through all the entries in the Map.
它工作正常,有没有其他方法可以在不遍历 Map 中的所有条目的情况下执行此操作。
采纳答案by ruakh
You can just use putAll
:
你可以只使用putAll
:
filterMapObj.putAll(filterMap);
(See the Javadoc.)
(请参阅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);
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.)
它创建了一个不可修改的“视图” filterMap
。这是更严格,当然,它不会让你修改filterMapObj
和filterMap
独立。(filterMapObj
不能修改,任何修改filterMap
都会影响filterMapObj
。)
回答by Prasad Kharkar
You can use the wildcard operator for this.
Define filterMapObj
as Map<String, ? extends Object> filterMapObj
and you can directly assign the filterMap
to it. You can learn about generics wildcard operator
您可以为此使用通配符运算符。定义filterMapObj
为Map<String, ? extends Object> filterMapObj
,您可以直接将其分配filterMap
给它。您可以了解泛型通配符运算符
回答by PengPeng.Xu
You can use putAll method to solve the problem.The Object is the father class of all objects,so you can use putAll without convert.
可以使用putAll方法来解决这个问题。Object是所有对象的父类,所以不用转换就可以使用putAll。
回答by Asanka Siriwardena
You can simply write
你可以简单地写
Map<String, Object> filterMapObj = new HashMap<>(filterMap);