22

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.

3
  • The Integer class is the same thing as an int really. It wraps and unwraps an int for you, so, hypothetically, they are the same Commented May 9, 2017 at 18:27
  • Yes, but this method shows an error "The method add(Integer[]) in the type ArrayList<Integer[]> is not applicable for the arguments (int[])" when I try to append the mapped array to my ArrayList of Integers. Commented May 9, 2017 at 18:30
  • 1
    This question seems relevant to your doubt. Commented May 9, 2017 at 18:31

2 Answers 2

29

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);
Sign up to request clarification or add additional context in comments.

Comments

5

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));

2 Comments

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.
You can map instead of boxing and mapInt: 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.