Converting java.util.Properties to HashMap<String,String>
This is because Properties
extends Hashtable<Object, Object>
(which, in turn, implements Map<Object, Object>
). You attempt to feed that into a Map<String, String>
. It is therefore incompatible.
You need to feed string properties one by one into your map...
For instance:
for (final String name: properties.stringPropertyNames())
map.put(name, properties.getProperty(name));
The efficient way to do that is just to cast to a generic Map as follows:
Properties props = new Properties();
Map<String, String> map = (Map)props;
This will convert a Map<Object, Object>
to a raw Map, which is "ok" for the compiler (only warning). Once we have a raw Map
it will cast to Map<String, String>
which it also will be "ok" (another warning). You can ignore them with annotation @SuppressWarnings({ "unchecked", "rawtypes" })
This will work because in the JVM the object doesn't really have a generic type. Generic types are just a trick that verifies things at compile time.
If some key or value is not a String it will produce a ClassCastException
error. With current Properties
implementation this is very unlikely to happen, as long as you don't use the mutable call methods from the super Hashtable<Object,Object>
of Properties
.
So, if don't do nasty things with your Properties instance this is the way to go.
You could use Google Guava's:
com.google.common.collect.Maps.fromProperties(Properties)