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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:07:31  来源:igfitidea点击:

Converting Map<String,String> to Map<String,Object>

javastringoptimizationmaphashmap

提问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 filterMapObjand filterMapindependently. (filterMapObjcan't be modified, and any modifications to filterMapwill affect filterMapObjas well.)

它创建了一个不可修改的“视图” filterMap。这是更严格,当然,它不会让你修改filterMapObjfilterMap独立。(filterMapObj不能修改,任何修改filterMap都会影响filterMapObj。)

回答by Prasad Kharkar

You can use the wildcard operator for this. Define filterMapObjas Map<String, ? extends Object> filterMapObjand you can directly assign the filterMapto it. You can learn about generics wildcard operator

您可以为此使用通配符运算符。定义filterMapObjMap<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);