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));
Related videos on Youtube
Author by
Fiodor
Updated on September 15, 2022Comments
-
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
toInteger.valueOf
, but it seems that themapToInt()
method forces the primitive type.I have an ArrayList of arrays of Integers, so I cannot use primitive ints.
-
Alfabravo almost 7 yearsThis question seems relevant to your doubt.
-
-
Fiodor almost 7 yearsThanks 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 almost 7 yearsYou can
map
instead ofbox
ing andmapInt
:String [] myArray = {"1", "2", "3", "4"};
Integer[] integerList =Arrays.stream(myArray).map(Integer::valueOf).toArray(Integer[]::new); System.out.print(integerList[0].getClass()); //output: class java.lang.Integer