转换Map< String,String>映射到< String,Object> [英] Converting Map<String,String> to Map<String,Object>

查看:124
本文介绍了转换Map< String,String>映射到< 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的不可修改的视图".当然,这更具限制性,因为它不允许您单独修改filterMapObjfilterMap. (不能修改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&lt; String,String&gt;映射到&lt; String,Object&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆