Jam*_*mes 2 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());
}
Run Code Online (Sandbox Code Playgroud)
我上面的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
Run Code Online (Sandbox Code Playgroud)
是否有一种简单的方法允许我使用lambdas或其他方法从String数组到Integer数组?
mapToInt(Integer::parseInt).toArray()
返回int[]
数组,因为matToInt
generate IntStream
但是int[]
数组不能通过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
Run Code Online (Sandbox Code Playgroud)
正如所指出的其他人,mapToInt
返回IntStream
其toArray
方法将返回int[]
,而不是Integer[]
.除此之外,还有一些其他需要改进的地方:
Integer [] toSort = new Integer [] {};
Run Code Online (Sandbox Code Playgroud)
是一种初始化数组的不必要的复杂方法.使用其中之一
Integer[] toSort = {};
Run Code Online (Sandbox Code Playgroud)
要么
Integer[] toSort = new Integer[0];
Run Code Online (Sandbox Code Playgroud)
但是你根本不应该初始化它,如果你打算覆盖它的话.如果要为异常情况设置回退值,请在异常处理程序中执行赋值:
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];
}
Run Code Online (Sandbox Code Playgroud)
此外,请注意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];
}
Run Code Online (Sandbox Code Playgroud)
Pattern
指内部使用java.util.regex.Pattern
的同一类String.split
.
归档时间: |
|
查看次数: |
3535 次 |
最近记录: |