如何使用Lambda将String数组转换为Integer数组?

时间:2015-09-11 17:37:51

标签: java arrays lambda java-8

我正在尝试使用lambda表达式将String数组转换为Integer数组。

我在下面提供了我的代码,以及到目前为止我所尝试的内容的简要说明:

String [] inputData = userInput.split("\\s+");
Integer [] toSort = new Integer [] {};
try {
    toSort = Arrays.asList(inputData).stream().mapToInt(Integer::parseInt).toArray();
}catch(NumberFormatException e) {
    System.out.println("Error. Invalid input!\n" + e.getMessage());
}

我上面的lamba表达式是一个映射到int数组的表达式,这不是我想要的,在编译这段代码时我得到以下错误信息:

BubbleSort.java:13: error: incompatible types: int[] cannot be converted to Integer[]
            toSort = Arrays.asList(inputData).stream().mapToInt(Integer::parseIn
t).toArray();

          ^
1 error

是否有一种简单的方法可以让我使用lambdas或其他方法从String数组到Integer数组?

3 个答案:

答案 0 :(得分:5)

mapToInt(Integer::parseInt).toArray()返回int[]数组,因为matToInt生成IntStreamint[]数组不能被Integer[]引用使用(拳击)仅适用于基本类型,而不是基本类型。

您可以使用的是

import java.util.stream.Stream;
//...
toSort = Stream.of(inputData)
               .map(Integer::valueOf) //value of returns Integer, parseInt returns int
               .toArray(Integer[]::new); // to specify type of returned array

答案 1 :(得分:5)

正如其他人已经指出的那样,mapToInt会返回IntStream,其toArray方法将返回int[]而不是Integer[]。除此之外,还有其他一些需要改进的地方:

Integer [] toSort = new Integer [] {};

是初始化数组的一种不必要的复杂方法。使用

Integer[] toSort = {};

Integer[] toSort = new Integer[0];

但是你根本不应该初始化它,如果你打算覆盖它的话。如果要为异常情况设置回退值,请在异常处理程序中执行赋值:

String[] inputData = userInput.split("\\s+");
Integer[] toSort;
try {
    toSort = Arrays.stream(inputData).map(Integer::parseInt).toArray(Integer[]::new);
}catch(NumberFormatException e) {
    System.out.println("Error. Invalid input!\n" + e.getMessage());
    toSort=new Integer[0];
}

此外,请注意您在案例中不需要String[]数组:

Integer[] toSort;
try {
    toSort = Pattern.compile("\\s+").splitAsStream(userInput)
        .map(Integer::parseInt).toArray(Integer[]::new);
}catch(NumberFormatException e) {
    System.out.println("Error. Invalid input!\n" + e.getMessage());
    toSort=new Integer[0];
}

Pattern是指java.util.regex.Pattern,它与String.split内部使用的是同一类。

答案 2 :(得分:2)

如果您想要Integer数组,请不要映射到IntStream,映射到Stream<Integer>

toSort = Arrays.asList(inputData).stream().map(Integer::valueOf).toArray(Integer[]::new);
相关问题