Convert String array to Map using Java 8 Lambda expressions
You can modify your solution to collect the Stream
of String
arrays into a Map
(instead of using forEach
) :
Map<String, Double> kvs =
Arrays.asList("a:1.0", "b:2.0", "c:3.0")
.stream()
.map(elem -> elem.split(":"))
.collect(Collectors.toMap(e -> e[0], e -> Double.parseDouble(e[1])));
Of course this solution has no protection against invalid input. Perhaps you should add a filter just in case the split String has no separator :
Map<String, Double> kvs =
Arrays.asList("a:1.0", "b:2.0", "c:3.0")
.stream()
.map(elem -> elem.split(":"))
.filter(elem -> elem.length==2)
.collect(Collectors.toMap(e -> e[0], e -> Double.parseDouble(e[1])));
This still doesn't protect you against all invalid inputs (for example "c:3r"
would cause NumberFormatException
to be thrown by parseDouble
).