5

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.

Andrea Catania
  • 1,361
  • 3
  • 21
  • 37

3 Answers3

18

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()
    ));
Lukasz Wiktor
  • 19,644
  • 5
  • 69
  • 82
  • So easy... I had tried in this way: Collectors.toMap( e -> (String) e.getKey(), (String) e.getValue()) but ofcourse not work... Very very thanks, I have last question, have you a guide for lambda expression? – Andrea Catania May 27 '14 at 11:21
  • 2
    @AndreaCatania I started with javadoc and tutorials from Oracle: http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html and http://docs.oracle.com/javase/tutorial/collections/streams/index.html This article was also very helpful: http://www.techempower.com/blog/2013/03/26/everything-about-java-8/ – Lukasz Wiktor May 27 '14 at 11:39
6

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.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • what is the efficient way between constructor or lambda? – Andrea Catania May 27 '14 at 11:28
  • @AndreaCatania - I'd say let the system do it if you can, you should never optimise until you have proved that optimisation is necessary, so use the constructor. – OldCurmudgeon May 27 '14 at 11:30
  • 1
    You wrote `new HashMap(p)` (raw type), escaping generic type analysis; this is why your code only produces a warning and not an error, at least in Eclipse: "The expression of type `HashMap` needs unchecked conversion to conform to `Map`" – Marko Topolnik May 27 '14 at 11:32
  • so the best solution is to use HashMap( p )? – Andrea Catania May 27 '14 at 11:32
1

for those who want to use forEach

HashMap<String, String> propMap = new HashMap<>();
prop.forEach((key, value)-> {
   propMap.put( (String)key, (String)value);
});
niraj.nijju
  • 616
  • 1
  • 8
  • 17