简体   繁体   English

转换地图<String,String>到地图<String,Object>

[英]Converting Map<String,String> to Map<String,Object>

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> .我需要的是我想将Map<String, String>转换为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.它工作正常,有没有其他方法可以在不遍历 Map 中的所有条目的情况下执行此操作。

Instead of writing your own loop that calls put , you can putAll , which does the same thing:无需编写自己的调用put循环,您可以putAll ,它执行相同的操作:

filterMapObj.putAll(filterMap);

(See the Javadoc .) (请参阅Javadoc 。)

And as Asanka Siriwardena points out in his/her answer, if your plan is to populate filterMapObj immediately after creating it, then you can use the constructor that does that automatically:正如 Asanka Siriwardena 在他/她的回答中指出的那样,如果您的计划是在创建filterMapObj后立即填充它,那么您可以使用自动执行此操作的构造函数:

filterMapObj = new HashMap<>(filterMap);

But to be clear, the above are 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 (eg, 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 .这创建了filterMap的不可修改的“视图”。 That's more restrictive, of course, in that it won't let you modify filterMapObj and filterMap independently.当然,这更具限制性,因为它不会让您独立修改filterMapObjfilterMap ( filterMapObj can't be modified, and any modifications to filterMap will affect filterMapObj as well.) filterMapObj不能修改,对filterMap任何修改也会影响filterMapObj 。)

You can use the wildcard operator for this.您可以为此使用通配符运算符。 Define filterMapObj as Map<String, ? extends Object> filterMapObjfilterMapObj定义为Map<String, ? extends Object> filterMapObj Map<String, ? extends Object> filterMapObj and you can directly assign the filterMap to it. Map<String, ? extends Object> filterMapObj并且您可以直接将filterMap分配给它。 You can learn about generics wildcard operator您可以了解泛型通配符运算符

你可以简单地写

Map<String, Object> filterMapObj = new HashMap<>(filterMap);

可以使用putAll方法来解决这个问题。Object是所有对象的父类,所以不用转换就可以使用putAll。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM