Java map an array of Strings to an array of Integers

牧云@^-^@ 提交于 2021-02-07 12:15:24

问题


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.


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



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


来源:https://stackoverflow.com/questions/43877296/java-map-an-array-of-strings-to-an-array-of-integers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!