Alex Rivera | Logout

What's the best way to extract a single value from a Set in groovy?

Asked 2011-03-04T19:57:38.310
13

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()
Edit
Report

2 Answers

20

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

set.iterator().next()
answered 2011-03-07T09:15:20.707
16

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.

answered 2011-03-04T20:19:25.103

Your Answer