[英]Map Object Array to Int Array
I'm trying to map and filter my Object[] array to int[] array. 我正在尝试将我的Object []数组映射并过滤到int []数组。 Works great, if an object is an int, but throws cast exception if not.
如果对象是int,则工作得很好,但如果没有,则抛出强制转换异常。 I'm wondering if I can somehow attach an try/catch in lambda expression?
我想知道我是否能以某种方式在lambda表达式中附加try / catch? Here's my code:
这是我的代码:
b[i] = Arrays.stream(item).mapToInt(e -> (int) e).filter(e -> e % 2 != 0).toArray();
or better way is just to try/catch whole block? 或更好的方法是尝试/捕获整块?
Wy不过滤整数对象?
.filter(i -> i instanceof Integer).mapToInt(e -> (int) e)
Use filter()
to remove non-numerical values, then convert to Number
and call the intValue()
method. 使用
filter()
删除非数值,然后转换为Number
并调用intValue()
方法。
int[] ints = Arrays.stream(objects)
.filter(Number.class::isInstance)
.map(Number.class::cast)
.mapToInt(Number::intValue)
.toArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.