Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Properties and lambda collect

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.

like image 875
Andrea Catania Avatar asked May 27 '14 11:05

Andrea Catania


People also ask

What is Properties collection in Java?

Properties is a subclass of Hashtable. It is used to maintain a list of values in which the key is a string and the value is also a string i.e; it can be used to store and retrieve string type data from the properties file. Properties class can specify other properties list as it's the default.

What does -> mean in Java?

Basically, the -> separates the parameters (left-side) from the implementation (right side). The general syntax for using lambda expressions is. (Parameters) -> { Body } where the -> separates parameters and lambda expression body.

Does lambda expression improve performance?

Oracle claims that use of lambda expressions also improve the collection libraries making it easier to iterate through, filter, and extract data from a collection. In addition, new concurrency features improve performance in multicore environments.

Can lambda have return statement in Java?

A return statement is not an expression in a lambda expression. We must enclose statements in braces ({}). However, we do not have to enclose a void method invocation in braces. The return type of a method in which lambda expression used in a return statement must be a functional interface.


1 Answers

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()
    ));
like image 63
Lukasz Wiktor Avatar answered Sep 30 '22 14:09

Lukasz Wiktor