Java Properties and lambda collect
13,705
Solution 1
Use Collectors.toMap
Properties prop = new Properties();
prop.load(new FileInputStream( path ));
Map<String, String> mapProp = prop.entrySet().stream().collect(
Collectors.toMap(
e -> (String) e.getKey(),
e -> (String) e.getValue()
));
Solution 2
Not actually an answer but may be useful to know for others passing by.
Since Properties
extends Hashtable<Object,Object>
which implements Map<K,V>
you should not need to do anything other than:
Properties p = new Properties();
Map<String,String> m = new HashMap(p);
Not quite sure why no warnings are offered for this code as it implies a cast from Map<Object,Object>
to Map<String,String>
is acceptable but I suspect that is a separate question.
Solution 3
for those who want to use forEach
HashMap<String, String> propMap = new HashMap<>();
prop.forEach((key, value)-> {
propMap.put( (String)key, (String)value);
});
Author by
Andrea Catania
Updated on August 08, 2022Comments
-
Andrea Catania over 1 year
I have a method that convert Properties into hashmap in this way (i know it's wrong)
Map<String, String> mapProp = new HashMap<String, String>(); Properties prop = new Properties(); prop.load(new FileInputStream( path )); prop.forEach( (key, value) -> {mapProp.put( (String)key, (String)value );} ); return mapProp;
My idea is that mapping in a way like this:
Properties prop = new Properties(); prop.load(new FileInputStream( path )); Map<String, String> mapProp = prop.entrySet().stream().collect( /*I don't know*/ ); return mapProp;
How write a lambda expression for do that?
Thanks all in advance
Andrea.