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

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


List<Integer> intList = strList.stream()                               .map(Integer::valueOf)                               .collect(Collectors.toList());


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 listspublic static <T, U> List<U> convertList(List<T> from, Function<T, U> func) {    return from.stream().map(func).collect(Collectors.toList());}//for arrayspublic static <T, U> U[] convertArray(T[] from,                                       Function<T, U> func,                                       IntFunction<U[]> generator) {    return Arrays.stream(from).map(func).toArray(generator);}

And use it like this:

//for listsList<String> stringList = Arrays.asList("1","2","3");List<Integer> integerList = convertList(stringList, s -> Integer.parseInt(s));//for arraysString[] stringArr = {"1","2","3"};Double[] doubleArr = convertArray(stringArr, Double::parseDouble, Double[]::new);


Note that s -> Integer.parseInt(s) could be replaced with Integer::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 and collect(...) or toArray() wrap the stream back up into an array or collection.

Venkat Subramaniam's talk (video) explains it better than me.

1 Convert List<String> to List<Integer>

List<String> l1 = Arrays.asList("1", "2", "3");List<Integer> r1 = l1.stream().map(Integer::parseInt).collect(Collectors.toList());// the longer full lambda version:List<Integer> r1 = l1.stream().map(s -> Integer.parseInt(s)).collect(Collectors.toList());

2 Convert List<String> to int[]

int[] r2 = l1.stream().mapToInt(Integer::parseInt).toArray();

3 Convert String[] to List<Integer>

String[] a1 = {"4", "5", "6"};List<Integer> r3 = Stream.of(a1).map(Integer::parseInt).collect(Collectors.toList());

4 Convert String[] to int[]

int[] r4 = Stream.of(a1).mapToInt(Integer::parseInt).toArray();

5 Convert String[] to List<Double>

List<Double> r5 = Stream.of(a1).map(Double::parseDouble).collect(Collectors.toList());

6 (bonus) Convert int[] to String[]

int[] a2 = {7, 8, 9};String[] r6 = Arrays.stream(a2).mapToObj(Integer::toString).toArray(String[]::new);

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.