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

落花浮王杯 提交于 2019-12-09 14:00:02

问题


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

        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.


回答1:


You can just use putAll:

filterMapObj.putAll(filterMap);

(See the 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.)




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/21037263/converting-mapstring-string-to-mapstring-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!