ataylor - 2 months ago 13

Groovy Question

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

Answer

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.