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?

6
  • What is expected behaviour, when some objects are ints and other are not? Commented Feb 15, 2017 at 10:27
  • Yeah, of course. Im just wondering how to try/catch that without dropping whole array. Commented Feb 15, 2017 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. Commented Feb 15, 2017 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? Commented Feb 15, 2017 at 10:30
  • 1
    It’s become an aside now, but you may use try/catch within your lambda; could be useful in other cases. Commented Feb 15, 2017 at 10:58

2 Answers 2

5

Wy not filter objects that are Integers?

.filter(i -> i instanceof Integer).mapToInt(e -> (int) e)
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, why didn't I think of that? Thanks!
Alternatively, without use of lambda: .filter(Integer.class::isInstance) .mapToInt(Integer.class::cast)
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();

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.