Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java map an array of Strings to an array of Integers

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.

like image 307
Fiodor Avatar asked May 09 '17 18:05

Fiodor


People also ask

How do you convert an array of strings to an array of integers in Java?

The string. split() method is used to split the string into various sub-strings. Then, those sub-strings are converted to an integer using the Integer. parseInt() method and store that value integer value to the Integer array.

Can I put an array in a HashMap?

In a HashMap, keys and values can be added using the HashMap. put() method. We can also convert two arrays containing keys and values into a HashMap with respective keys and values.


1 Answers

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);
like image 166
Flown Avatar answered Sep 21 '22 05:09

Flown