如何将 Map<Object, Object> 转换为 Map<String, String> 在 Java 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17208346/
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-11-01 01:19:16  来源:igfitidea点击:

How to convert Map<Object, Object> to Map<String, String> in java?

javamapinputstream

提问by M.S.Naidu

I have the Map of type Object, i need to convert this map into the type String.

我有 Object 类型的 Map,我需要将此映射转换为 String 类型。

Map<String, String> map = new HashMap<String, String>();    
Properties properties = new Properties();    
properties.load(instream);     

Can any body please tell me, how to assign the properties to above map?

任何人都可以告诉我,如何将属性分配给上面的地图?

Thanks & Regards, Msnaidu

感谢和问候, Msnaidu

回答by dkateros

Map<String, String> properties2Map(Properties p) {
            Map<String, String> map = new HashMap<String, String>();
            for(Map.Entry<Object, Object> entry : p.entrySet()) {
                String key = (String) entry.getKey(); //not really unsafe, since you just loaded the properties
                map.put(key, p.getProperty(key));
            }
            return map;
}

I also like to use utility methods with type arguments to walk around generic type invariance and do some "downcasting" or "upcasting" (when I KNOW it is safe to do so). In this case:

我还喜欢使用带有类型参数的实用程序方法来绕过泛型类型不变性并执行一些“向下转换”或“向上转换”(当我知道这样做是安全的时)。在这种情况下:

@SuppressWarnings("unchecked")
<A, B extends A> Map<B, B> downCastMap(Map<A,A> map) {
    return (Map<B, B>)map;
}

Then you can write

然后你可以写

Properties p = ...
Map<String, String> map = downCastMap(p);

回答by Andrzej Doyle

The cleanest way to add the properties to the map would be (following on from your example):

将属性添加到地图的最干净的方法是(按照您的示例):

for (String propName : properties.stringPropertyNames()) {
    map.put(propName, properties.getProperty(propName));
}

This works nicely in this particular case, because the Propertiesobject is really a map containing String keys and values, as the getPropertymethod makes clear. It's only declared as Map<Object, Object>for horrible backwards-compatibility reasons.

这在这种特殊情况下效果很好,因为该Properties对象实际上是一个包含字符串键和值的映射,正如该getProperty方法所明确的那样。它只是Map<Object, Object>出于可怕的向后兼容性原因而声明的。

By using the Properties-specific methods, rather than treating this as just a Map<Object, Object>, you can populate your Map<String, String>with perfect type-safety (rather than having to cast).

通过使用特定于属性的方法,而不是仅将其视为 a Map<Object, Object>,您可以Map<String, String>使用完美的类型安全(而不必强制转换)填充您的。

回答by Tardis Xu

You can directly convert:

您可以直接转换:

Properties properties = new Properties();
Map<String, String> map = new HashMap<String, String>((Map)properties);

回答by Johnny

With Java 8and the addition of Streams, I would suggest you to use the APIs Steam provides

使用Java 8和添加Streams,我建议您使用 Steam 提供的 API

Here, we assuming that each of the values actually are String objects, the cast to String should be safe:

在这里,我们假设每个值实际上都是 String 对象,那么转换为 String 应该是安全的:

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

Map<String,String> stringifiedMapSafe = map.entrySet().stream()
     .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));

Now, in case we not sure that all the element are String, and we want to filter the key/values with null:

现在,如果我们不确定所有元素都是String,并且我们想用 过滤键/值null

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

Map<String,String> stringifiedMapNotSafe = map.entrySet().stream()
             .filter(m -> m.getKey() != null && m.getValue() !=null)
             .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));

回答by Andreas Dolk

Because we knowthat the Properties are a String-to-String mapping already, it's save to do it with rawtype and unchecked conversion. Just leave a comment:

因为我们知道Properties 已经是一个字符串到字符串的映射,所以使用原始类型和未经检查的转换来做它是省事的。只需发表评论:

    Properties properties = new Properties();    
    properties.load(instream); 

    @SuppressWarnings({ "rawtypes", "unchecked" })
    // this is save because Properties have a String to String mapping
    Map<String, String> map = new HashMap(properties);

回答by amicngh

Map<String,String> getPropInMap(Properties prop){       
    Map<String, String> myMap = new HashMap<String, String>();
    for (Object key : prop .keySet()) {
        myMap.put(key.toString(), prop .get(key).toString());
    }       
    return myMap;
}

回答by ovi

Iterate over Map Object, take k v, make them string and put it to a Map String.

迭代 Map 对象,获取 kv,将它们设为字符串并将其放入 Map String。

Map<Object,Object> map1; // with object k,v
Map<String, String> mapString = new HashMap<String, String>();
for (Object key : map1.keySet()) {
                String k = key.toString();
                String v = mmap1.get(key).toString();
                mapString.put(k, v);
            }