简体   繁体   中英

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

I have the Map of type Object, i need to convert this map into the type 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

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);

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 Properties object is really a map containing String keys and values, as the getProperty method makes clear. It's only declared as Map<Object, Object> for horrible backwards-compatibility reasons.

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).

You can directly convert:

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

Because we know that 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 = 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);

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

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

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 :

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()));
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;
}

Iterate over Map Object, take kv, make them string and put it to a 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);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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