I'm trying to map and filter my Object[] array to int[] array. Works great, if an object is an int, but throws cast exception if not. I'm wondering if I can somehow attach an try/catch in lambda expression? 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.
int[] ints = Arrays.stream(objects)
.filter(Number.class::isInstance)
.map(Number.class::cast)
.mapToInt(Number::intValue)
.toArray();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.