Since Java 8 comes with powerful lambda expressions,
I would like to write a function to convert a List/array of Strings to array/List of Integers, Floats, Doubles etc..
In normal Java, it would be as simple as
for(String str : strList){
intList.add(Integer.valueOf(str));
}
But how do I achieve the same with a lambda, given an array of Strings to be converted to an array of Integers.
I didn't find it in the previous answers, so, with Java 8 and streams:
Convert
String[]
toInteger[]
:You could create helper methods that would convert a list (array) of type
T
to a list (array) of typeU
using themap
operation onstream
.And use it like this:
Note that
s -> Integer.parseInt(s)
could be replaced withInteger::parseInt
(see Method references)The helper methods from the accepted answer are not needed. Streams can be used with lambdas or usually shortened using Method References. Streams enable functional operations.
map()
converts the elements andcollect(...)
ortoArray()
wrap the stream back up into an array or collection.Venkat Subramaniam's talk (video) explains it better than me.
1 Convert
List<String>
toList<Integer>
2 Convert
List<String>
toint[]
3 Convert
String[]
toList<Integer>
4 Convert
String[]
toint[]
5 Convert
String[]
toList<Double>
6 (bonus) Convert
int[]
toString[]
Lots more variations are possible of course.
Also see Ideone version of these examples. Can click fork and then run to run in the browser.