Finding an odd number from int[] array using Stream

  • A+
Category:Languages

I created an array and trying to use streams for finding the first odd number as follows:

int[] arr = new int[]{2, 4, 6, 8, 9, 12}; int oddOne = Stream.of(arr).filter(i -> i % 2 != 0).findFirst().get();                                    // fails above 

Error: | incompatible types: int[] cannot be converted to int

What am I doing wrong? How do I fix this?

 


You need to use Arrays.stream():

Arrays.stream(arr).filter(i -> i % 2 != 0).findFirst().getAsInt(); 

Which:

Returns a sequential IntStream with the specified array as its source.

As of now you are using the overloaded method Stream.of(T t) which simply:

Returns a sequential Stream containing a single element.

So it will only be a Stream of the single int[]


Also as nullpointer noted, calling get() without ensuring there is in fact an odd number in the Array will cause an error. It is best to use orElse() to return a default value if no odd number is present

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: