Issue
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?
Solution
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
Answered By - GBlodgett
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.