Reddy Reddy - 2 years ago 107
Java Question

Lambda expression to convert array/List of String to array/List of Integers

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){

But how do I achieve the same with a lambda, given an array of Strings to be converted to an array of Integers.

Answer Source

You could create helper methods that would convert a list (array) of type T to a list (array) of type U using the map operation on stream.

//for lists
public static <T, U> List<U> convertList(List<T> from, Function<T, U> func){

//for arrays
public static <T, U> U[] convertArray(T[] from, Function<T, U> func, 
                                       IntFunction<U[]> generator){

And use it like this:

//for lists
List<String> stringList = Arrays.asList("1","2","3");
List<Integer> integerList = convertList(stringList, s -> Integer.parseInt(s));

//for arrays
String[] stringArr = {"1","2","3"};
Double[] doubleArr = convertArray(stringArr, Double::parseDouble, Double[]::new);

Note that s -> Integer.parseInt(s) could be replace with Integer::parseInt (see Method references)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download