返回集合中唯一元素的正确方法
我有以下情况:
Set<Element> set = getSetFromSomewhere();
if (set.size() == 1) {
// return the only element
} else {
throw new Exception("Something is not right..");
}
假设我无法更改 getSetFromSomewhere() 的返回类型,是否有比
- 迭代集合并返回 更好或更正确的方法来返回集合中的唯一元素立即
- 从集合中创建一个列表并调用
.get(0)
I have the following kind of situation:
Set<Element> set = getSetFromSomewhere();
if (set.size() == 1) {
// return the only element
} else {
throw new Exception("Something is not right..");
}
Assuming I cannot change the return type of getSetFromSomewhere()
, is there a better or more correct way to return the only element in the set than
- Iterating over the set and returning immediately
- Creating a list from the set and calling
.get(0)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
Iterator
来获取唯一元素并验证集合是否仅包含一个元素(从而避免size()
调用和不必要的列表创建) :您通常会将其包装在自己的方法中:
请注意,此实现已经是 Google Guava 的一部分库(我强烈推荐,即使您不将其用于此特定代码)。更具体地说,该方法属于
Iterables
类:如果您对它的实现方式感到好奇,可以查看
Iterators
类源代码(中的方法Iterables
经常调用Iterators
中的方法):You can use an
Iterator
to both obtain the only element as well as verify that the collection only contains one element (thereby avoiding thesize()
call and the unnecessary list creation):You would typically wrap this up in its own method:
Note that this implementation is already part of Google's Guava libraries (which I highly recommend, even if you don't use it for this particular code). More specifically, the method belongs to the
Iterables
class:If you're curious about how it is implemented, you can look at the
Iterators
class source code (the methods inIterables
often call methods inIterators
):最好的一般解决方案(您不知道实际的集合类)是:
如果已知集合类是
SortedSet
(例如TreeSet< /code> 或
ConcurrentSkipListSet
),那么更好的解决方案是:在这两种情况下,如果集合为空,都会抛出异常;检查javadoc。使用
Collection.isEmpty()
可以避免异常。对于
HashSet
或LinkedHashSet
,第一个解决方案在时间和空间上都是O(1)
,但对于其他类型的集合来说通常更糟。第二个时间复杂度为
O(logN)
,并且TreeSet
或ConcurrentSkipListSet
不使用空间。从设置的内容创建列表然后调用
List.get(0)
的方法提供了一个糟糕的解决方案,因为第一步是一个O(N)
操作,两者在时间和空间上。我没有注意到
N
实际上是1
。但即便如此,创建迭代器可能比创建临时列表更便宜。The best general solution (where you don't know the actual set class) is:
If the set class is known to be a
SortedSet
(e.g. aTreeSet
orConcurrentSkipListSet
), then a better solution is:In both cases, an exception will be thrown if the set is empty; check the javadocs. The exception can be avoided using
Collection.isEmpty()
.The first solution is
O(1)
in time and space for aHashSet
orLinkedHashSet
, but typically worse for other kinds of set.The second one is
O(logN)
in time , and uses no space forTreeSet
orConcurrentSkipListSet
.The approach of creating a list from the set contents and then calling
List.get(0)
gives a poor solution since the first step is anO(N)
operation, both in time and space.I failed to notice that
N
is actually1
. But even so, creating an iterator is likely to be less expensive than creating a temporary list.你可以抓住迭代器:
You could grab the iterator:
在 Java 8 中,我们可以这样做:
但是,请记住在
Optional.get()
抛出NoSuchElementException
之前检查集合的大小In Java 8, we can do like below:
But, remember to check the size of set before as
Optional.get()
throwsNoSuchElementException