117

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.

0

10 Answers 10

147
List<Integer> intList = strList.stream()
                               .map(Integer::valueOf)
                               .collect(Collectors.toList());
3
  • 5
    Can you explain this a little?
    – Unheilig
    Oct 20, 2014 at 2:07
  • 1
    This is converting a list of String into a stream then mapping/ converting every element of the list into Integer then collecting into a list.
    – hemanto
    Dec 13, 2017 at 10:36
  • 5
    This should be the accepted answer, since the point of lambdas (the original question asks for a lambda expression) is to avoid defining a new function. On top of which, this answer elegantly uses the existing Integer::valueOf function Jun 1, 2018 at 18:37
132

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) {
    return from.stream().map(func).collect(Collectors.toList());
}

//for arrays
public 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 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 replaced with Integer::parseInt (see Method references)

2
  • 5
    If you're using Guava, you can also use Lists.transform().
    – Alexandros
    Sep 22, 2015 at 9:53
  • Very good example. The function turns the code more versatile and powerful. Thks!!! Jul 11, 2019 at 17:28
37

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.

7

EDIT: As pointed out in the comments, this is a much simpler version: Arrays.stream(stringArray).mapToInt(Integer::parseInt).toArray() This way we can skip the whole conversion to and from a list.


I found another one line solution, but it's still pretty slow (takes about 100 times longer than a for cycle - tested on an array of 6000 0's)

String[] stringArray = ...
int[] out= Arrays.asList(stringArray).stream().map(Integer::parseInt).mapToInt(i->i).toArray();

What this does:

  1. Arrays.asList() converts the array to a List
  2. .stream converts it to a Stream (needed to perform a map)
  3. .map(Integer::parseInt) converts all the elements in the stream to Integers
  4. .mapToInt(i->i) converts all the Integers to ints (you don't have to do this if you only want Integers)
  5. .toArray() converts the Stream back to an array
1
  • 13
    You don't need steps 1 and 4: Arrays.stream(stringArray).mapToInt(Integer::parseInt).toArray()
    – xehpuk
    Oct 16, 2015 at 16:05
6

For List :

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

For Array :

int[] intArray = Arrays.stream(stringArray).mapToInt(Integer::valueOf).toArray();
2

You can also use,

List<String> list = new ArrayList<>();
    list.add("1");
    list.add("2");
    list.add("3");

    Integer[] array = list.stream()
        .map( v -> Integer.valueOf(v))
        .toArray(Integer[]::new);
0

I didn't find it in the previous answers, so, with Java 8 and streams:

Convert String[] to Integer[]:

Arrays.stream(stringArray).map(Integer::valueOf).toArray(Integer[]::new)
0

I used maptoInt() with Lambda operation for converting string to Integer

int[] arr = Arrays.stream(stringArray).mapToInt(item -> Integer.parseInt(item)).toArray();
-1

In addition - control when string array doesn't have elements:

Arrays.stream(from).filter(t -> (t != null)&&!("".equals(t))).map(func).toArray(generator) 
-3

Arrays.toString(int []) works for me.

1
  • I doesn't answer the question: "How to achieve this with lambdas". Jan 31, 2019 at 0:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.