Arrays.getOnlyElement()?
是否有相当于 Collections.getOnlyElement() 适用于数组吗?
我知道这是一个实现起来很简单的函数,但 Collections.getOnlyElement() 也是如此,而且它是在番石榴中实现的。
Is there any equivalent to Collections.getOnlyElement() that works with arrays?
I'm aware it's a trivial function to implement, but Collections.getOnlyElement() is as well, and it's in guava.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Iterators.getOnlyElement(Iterators.forArray(array))
通过使用
Iterators.forArray
,您可以不需要将此数组的副本创建为列表,而是进行迭代在数组本身之上。然后使用 Iterators.getOnlyElement 从迭代器中获取第一个元素。Iterators.getOnlyElement(Iterators.forArray(array))
By using
Iterators.forArray
, you can bypass the need to create a copy of this array as a list, and instead iterate over the array itself. Then useIterators.getOnlyElement
to get the first element from an iterator.不太好,但仍然是一句台词:
Not nice but still a one-liner:
顺便提一句。如果像这样初始化,数组可以为非空且长度为 0:
Btw. an array can be non-null and have 0 length if initialized like this:
我不知道有任何库方法可以做到这一点。这似乎太简单了,不值得付出努力。
我遇到的最接近的(在拖网搜索结果页面之后)是这个 -
uk.org.retep.util.collections.ArrayUtils.getFirst
- 它与您所要求的语义不同。I don't know of any library method that does this. It seems too simple to be worth the effort.
The closest I've come across (after trawling pages of search results) is this -
uk.org.retep.util.collections.ArrayUtils.getFirst
- which has a different semantic to what you are asking for.