Java map an array of Strings to an array of Integers

19,197

Solution 1

Since String and Integer are both reference types you can simply call Stream::map to transform your array.

Integer[] boxed = Stream.of(myarray).map(Integer::valueOf).toArray(Integer[]::new);

Solution 2

you can use the Stream<Integer> boxed() method.

Stream<Integer> boxed() returns a Stream consisting of the elements of this stream, each boxed to an Integer.

ArrayList<Integer[]> resultSet = new ArrayList<>();
resultSet.add(Arrays.stream(myarray).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new));
Share:
19,197

Related videos on Youtube

Fiodor
Author by

Fiodor

Updated on September 15, 2022

Comments

  • Fiodor
    Fiodor over 1 year

    I found this code on SO to map strings to ints

    Arrays.stream(myarray).mapToInt(Integer::parseInt).toArray();
    

    But how do I make it map to Integer type not the primitive int?

    I tried switching from Integer.parseInt to Integer.valueOf, but it seems that the mapToInt() method forces the primitive type.

    I have an ArrayList of arrays of Integers, so I cannot use primitive ints.

    • Alfabravo
      Alfabravo almost 7 years
      This question seems relevant to your doubt.
  • Fiodor
    Fiodor almost 7 years
    Thanks a lot. Is there a way to do it more elegantly, though? Like for example in JavaScript myarray.map(function(e) {return parseInt(e);});? It seems like a lot of nested calls and intermediate types for just a simple String[] to Integer[] conversion.
  • Teena George
    Teena George almost 7 years
    You can map instead of boxing and mapInt: String [] myArray = {"1", "2", "3", "4"}; Integer[] integerList =Arrays.stream(myArray).map(Integer::valueOf).toArray(Intege‌​r[]::new); System.out.print(integerList[0].getClass()); //output: class java.lang.Integer