2

I have a Integer array as follows.

Integer[] nums = new Integer[]{1,2,3};
Integer inputNum = 3;

I would like to check if 3 is present here.

Was trying to use the below code, but it doesn't accept, Integer[].

IntStream.of(nums).anyMatch(num -> num == inputNum);

IntStream java.util.stream.IntStream.of(int... values)

Is there any better approach with Java 8?

3
  • Obviously num==num will match everything in the stream. Commented Feb 3, 2018 at 0:30
  • Sorry, typo. Updated. Commented Feb 3, 2018 at 0:30
  • 2
    With an Integer[] I reckon Arrays.asList(nums).contains(inputNum) is actually neater and likely more performant. This is a case of "when you have a hammer, everything looks like a nail". Commented Feb 3, 2018 at 0:32

1 Answer 1

2

You currently have an Integer[] therefore you can utilise Stream.of instead of IntStream.of.

IntStream.of only takes primitive integers whereas Stream.of is used for reference types.

boolean isPresent = Stream.of(nums).anyMatch(num -> Objects.equals(num, inputNum));

but I prefer to use Arrays.stream in this case instead of the XXX.of methods as in the ideal world you should only use them when you're going to provide explicit values.

boolean isPresent = Arrays.stream(nums).anyMatch(num -> Objects.equals(num, inputNum));
Sign up to request clarification or add additional context in comments.

8 Comments

As a said above, I think Arrays.asList(nums).contains(inputNum) is not only shorter but clearer in intent.
@BoristheSpider agreed, it's just that OP is asking for a java-8 solution.
Indeed. But I think that the request for a Java 8 solution is misguided in this case - rule of cool...
@user1578872 not sure, you'll have to run some tests.
@user1578872 for the given scenario I wouldn't worry about performance. pick whichever is more readable to you. Boris has provided a good and short solution which reads like problem statement and is shorter ;)
|

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.