How to convert map <object, object> to map <String, String> in java?

I have a map of type Object, I need to convert this map to type String.

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

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

Thanks and Regards, Msnaidu

0
source share
6 answers

The cleanest way to add properties to a map would be (as per your example):

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

This works well in this particular case, because an object Propertiesis really a map containing keys and String values, as the method does getProperty. It is declared Map<Object, Object>for terrible reasons for backward compatibility.

, , , Map<Object, Object>, Map<String, String> ( , ).

+3
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;
}

, "downcasting" "upcasting" ( , ). :

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

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

:

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

Since we know that properties are already String-to-String mappings, it saves this 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);
+1
source
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;
}
0
source

Go through the Map object, take kv, create a line and place it on the map line.

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);
            }
0
source

Source: https://habr.com/ru/post/1694207/


All Articles