将逗号分隔的字符串转换为整数数组的最佳方法

时间:2022-06-14 00:19:11

I have a comma separated string to convert to Integer array, I am using the below approach to do that, please suggest if there any simple way to do that.

我有一个逗号分隔的字符串转换为整数数组,我使用下面的方法来做这个,请建议如果有什么简单的方法。

Integer[] statusCodes = Arrays
        .stream(Arrays
                .stream(statusText.split(","))
                .map(String::trim)
                .mapToInt(Integer::valueOf)
                .toArray()
        )
        .boxed()
        .toArray(Integer[]::new);

2 个解决方案

#1


5  

You don't need outer stream. Also return type of Integer.valueOf is already Integer (it is Integer.parseInt which returns int) so you don't even need to boxed() it. Simply use map instead of mapToInt.

你不需要外流。还返回整型。valueOf已经是整数了(它是整数。parseInt返回int),因此您甚至不需要将它装箱()。只需使用map而不是mapToInt。

Integer[] array = Arrays.stream(" 1,2, 3, 4".split(","))
        .map(String::trim)
        .map(Integer::valueOf)
        .toArray(Integer[]::new);

System.out.println(Arrays.toString(array));

Output: [1, 2, 3, 4]

输出:[1、2、3、4]

#2


0  

Another version looks like follows:

另一个版本如下:

Integer[] statusCodes = Stream.of(statusText.split(",")).map(Integer::valueOf).toArray(Integer[]::new);

#1


5  

You don't need outer stream. Also return type of Integer.valueOf is already Integer (it is Integer.parseInt which returns int) so you don't even need to boxed() it. Simply use map instead of mapToInt.

你不需要外流。还返回整型。valueOf已经是整数了(它是整数。parseInt返回int),因此您甚至不需要将它装箱()。只需使用map而不是mapToInt。

Integer[] array = Arrays.stream(" 1,2, 3, 4".split(","))
        .map(String::trim)
        .map(Integer::valueOf)
        .toArray(Integer[]::new);

System.out.println(Arrays.toString(array));

Output: [1, 2, 3, 4]

输出:[1、2、3、4]

#2


0  

Another version looks like follows:

另一个版本如下:

Integer[] statusCodes = Stream.of(statusText.split(",")).map(Integer::valueOf).toArray(Integer[]::new);