从集合中返回唯一元素的正确方法 [英] The correct way to return the only element from a set

查看:270
本文介绍了从集合中返回唯一元素的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到以下情况:

Set<Element> set = getSetFromSomewhere();
if (set.size() == 1) {
    // return the only element
} else {
    throw new Exception("Something is not right..");
}

假设我无法更改的返回类型getSetFromSomewhere( ),是否有更好或更正确的方法来返回集合中唯一的元素而不是

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


  • 迭代结束设置并立即返回

  • 从集合中创建一个列表并调用 .get(0)

  • Iterating over the set and returning immediately
  • Creating a list from the set and calling .get(0)

推荐答案

您可以使用 Iterator 来获取唯一的元素以及验证集合只包含一个元素(从而避免 size()调用和不必要的列表创建):

You can use an Iterator to both obtain the only element as well as verify that the collection only contains one element (thereby avoiding the size() call and the unnecessary list creation):

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;

您通常会用自己的方法将其包装起来:

You would typically wrap this up in its own method:

public static <E> E getOnlyElement(Iterable<E> iterable) {
    Iterator<E> iterator = iterable.iterator();

    // The code I mentioned above...
}



<请注意,此实施已经是Google的番石榴图书馆(我高度推荐,即使您不将其用于此特定代码)。更具体地说,该方法属于 Iterables class

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:

Element element = Iterables.getOnlyElement(set);

如果您对如何实施它感到好奇,可以查看 迭代器类源代码 Iterables 中的方法通常调用 Iterators 中的方法) :

If you're curious about how it is implemented, you can look at the Iterators class source code (the methods in Iterables often call methods in 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());
  }

这篇关于从集合中返回唯一元素的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆