3

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?

ceroeps
  • 61
  • 1
  • 5
  • What is expected behaviour, when some objects are ints and other are not? – mishadoff Feb 15 '17 at 10:27
  • Yeah, of course. Im just wondering how to try/catch that without dropping whole array. – ceroeps Feb 15 '17 at 10:28
  • 2
    either use a `filter` so that you only map valid objects, or move `e -> (int) e` into its own method, where you place that `try/catch`. – Roland Feb 15 '17 at 10:29
  • Why would you use try/catch for that? Wouldn't make it so much more sense to use `filter` to get to find every array item which is a number before trying to convert it? – Tom Feb 15 '17 at 10:30
  • Possible duplicate of [Why can't I throw an exception in a Java 8 lambda expression?](http://stackoverflow.com/questions/37726874/why-cant-i-throw-an-exception-in-a-java-8-lambda-expression) – Thanga Feb 15 '17 at 10:31
  • 1
    It’s become an aside now, but you may use try/catch within your lambda; could be useful in other cases. – Ole V.V. Feb 15 '17 at 10:58

2 Answers2

5

Wy not filter objects that are Integers?

.filter(i -> i instanceof Integer).mapToInt(e -> (int) e)
Eugene
  • 117,005
  • 15
  • 201
  • 306
3

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();
Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45
  • 3
    Testing with `instanceof Number`, followed by casting to `int` is obviously broken. Either, test for `instanceof Integer` or use `.mapToInt(o -> ((Number)o).intValue())`. Using `.map(o -> (Number) o) .mapToInt(Number::intValue)` instead of a single `mapToInt` creates the impression of an irrational affinity to method references. – Holger Feb 15 '17 at 12:24