使用Stream从int []数组中查找奇数 [英] Finding an odd number from int[] array using Stream
问题描述
我创建了一个数组并尝试使用流来查找第一个奇数,如下所示:
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
错误:|不兼容的类型:int []无法转换为int
我做错了什么?我该如何解决这个问题?
What am I doing wrong? How do I fix this?
推荐答案
你需要使用 Arrays.stream()
:
You need to use Arrays.stream()
:
Arrays.stream(arr).filter(i -> i % 2 != 0).findFirst().getAsInt();
其中:
返回一个顺序
IntStream
,其中包含指定数组作为源。
Returns a sequential
IntStream
with the specified array as its source.
截至目前,您正在使用重载方法 Stream.of(T t)
简单地说:
As of now you are using the overloaded method Stream.of(T t)
which simply:
返回包含单个元素的顺序
Stream
。
所以它将只是单个 int []
同样在注明nullpointer时,调用 get()
而不确保<$ c $中实际存在奇数c>数组将导致错误。如果没有奇数,最好使用 orElse()
返回默认值
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
这篇关于使用Stream从int []数组中查找奇数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!