user1578872
user1578872

Reputation: 9038

Java8 check if a given integer is present in Integer[] array

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 doesnt accpet, Integer[].

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

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

Is there any better approach with Java 8?

Upvotes: 2

Views: 1397

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56433

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));

Upvotes: 2

Related Questions