M.S.Naidu M.S.Naidu - 5 months ago 27
Java Question

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

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

Thanks & Regards,


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