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.

3 Answers 3

19

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()
    ));
Sign up to request clarification or add additional context in comments.

2 Comments

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

4 Comments

what is the efficient way between constructor or lambda?
@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.
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<String,String>"
so the best solution is to use HashMap( p )?
1

for those who want to use forEach

HashMap<String, String> propMap = new HashMap<>();
prop.forEach((key, value)-> {
   propMap.put( (String)key, (String)value);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.