您可以使用 来获取唯一的元素,并验证集合是否只包含一个元素(从而避免调用和不必要的列表创建):Iterator
size()
Iterator<Element> iterator = set.iterator();
if (!iterator.hasNext()) {
throw new RuntimeException("Collection is empty");
}
Element element = iterator.next();
if (iterator.hasNext()) {
throw new RuntimeException("Collection contains more than one item");
}
return element;
您通常会将其包装在它自己的方法中:
public static <E> E getOnlyElement(Iterable<E> iterable) {
Iterator<E> iterator = iterable.iterator();
// The code I mentioned above...
}
请注意,此实现已经是Google的Guava库的一部分(我强烈建议您这样做,即使您不将其用于此特定代码)。更具体地说,该方法属于迭代类
:
Element element = Iterables.getOnlyElement(set);
如果你对它是如何实现的感到好奇,你可以看看迭代器
类的源代码(方法中经常调用方法):Iterables
Iterators
/**
* Returns the single element contained in {@code iterator}.
*
* @throws NoSuchElementException if the iterator is empty
* @throws IllegalArgumentException if the iterator contains multiple
* elements. The state of the iterator is unspecified.
*/
public static <T> T getOnlyElement(Iterator<T> iterator) {
T first = iterator.next();
if (!iterator.hasNext()) {
return first;
}
StringBuilder sb = new StringBuilder();
sb.append("expected one element but was: <" + first);
for (int i = 0; i < 4 && iterator.hasNext(); i++) {
sb.append(", " + iterator.next());
}
if (iterator.hasNext()) {
sb.append(", ...");
}
sb.append('>');
throw new IllegalArgumentException(sb.toString());
}