在 groovy 中从 Set 中提取单个值的最佳方法是什么?

发布于 2024-10-20 15:33:17 字数 269 浏览 4 评论 0原文

如果我知道一个 Set 包含单个元素,那么提取它的最佳方法是什么?我能想到的最好的办法是这样,但感觉不太好:

set = [1] as Set
e = set.toList()[0]
assert e == 1

如果我正在处理一个列表,我有很多很好的方法来获取元素,但这些方法似乎都不适用于集合:

def list = [1]
e = list[0]
(e) = list
e = list.head()

If I have a Set that I know contains a single element, what's the best way to extract it? The best I can come up with is this, but it doesn't feel very groovy:

set = [1] as Set
e = set.toList()[0]
assert e == 1

If I'm dealing with a list, I've got lots of nice ways to get the element, none of which seem to work with Sets:

def list = [1]
e = list[0]
(e) = list
e = list.head()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

枯叶蝶 2024-10-27 15:33:17

另一种可能性(适用于 Java 或 Groovy):

set.iterator().next()

One other possibility (which will work in Java or Groovy):

set.iterator().next()
骑趴 2024-10-27 15:33:17

有一些替代方案,但没有一个非常漂亮:

set.iterator()[0]
set.find { true }
set.collect { it }[0]

最后,如果保证该集合只有一项:

def e
set.each { e = it }

当然,根本问题是 Java 集合没有提供定义的顺序(如 Javadoc),因此无法获取第 n 个元素(讨论了在此问题这个)。因此,任何解决方案总是以某种方式将集合转换为列表。

我的猜测是,前两个选项中的任何一个都涉及最少的数据复制,因为它们不需要构造集合的完整列表,但对于单元素集,这几乎不应该是一个问题。

A few alternatives, none of them very pretty:

set.iterator()[0]
set.find { true }
set.collect { it }[0]

Finally, if it's guaranteed that that set has only one item:

def e
set.each { e = it }

The underlying issue, of course, is that Java Sets provide no defined order (as mentioned in the Javadoc), and hence no ability to get the nth element (discussed in this question and this one). Hence, any solution is always to somehow convert the set to a list.

My guess is that either of the first two options involve the least data-copying, as they needn't construct a complete list of the set, but for a one-element set, that should hardly be a concern.

甜尕妞 2024-10-27 15:33:17

从 Java 8 开始,这是另一个适用于 Java 和 Groovy 的解决方案:

set.stream().findFirst().get()

Since Java 8, here is another solution that will work for both Java and Groovy:

set.stream().findFirst().get()
回梦 2024-10-27 15:33:17

即使这个问题已经很老了,我还是分享我的一个更漂亮的解决方案。

(set as List).first()
(set as List)[0]

如果您需要考虑 null (不是这个问题的情况):

(set as List)?.first()
(set as List)?.get(index)

希望它有帮助! :)

Even when this question is quite old, I am sharing my just a bit prettier solution.

(set as List).first()
(set as List)[0]

If you need to take null into account (not the case in this question):

(set as List)?.first()
(set as List)?.get(index)

Hope it helps! :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文