J.Olufsen
J.Olufsen

Reputation: 13915

How to check if all elements of type integer is within given range using lambdas and streams in Java 8?

Given int[] A. Trying to make use all elements in array is greater or equals to -1000 and not greater than 1000 (incl.). How to do it properly?

My try:

boolean validIntegers = (Arrays.asList(A)).stream().allMatch(i -> (i >= -1000 && i <= 1000) );

Error:

enter image description here

Upvotes: 3

Views: 1736

Answers (1)

Pshemo
Pshemo

Reputation: 124275

Arrays.asList accepts T... but T as generic type can represent only Objects like int[], not primitive int. So T... represents {int[]} array, which contains internally array object, not array elements. So your stream contains array and you can't use any comparison operators on array.

To solve this problem and get stream of elements stored in array of ints you can use

  • IntStream.of(int...),
  • or Arrays.stream(yourArray) which supports double[] int[] long[] and T[].

So your code could be

boolean validIntegers = IntStream.of(A).allMatch(i -> (i >= -1000 && i <= 1000) );

Upvotes: 6

Related Questions