How to get first item from a java.util.Set?

Viewed 203583

I have a Set instance:

Set<String> siteIdSet = (Set<String>) pContext.getParent().getPropertyValue(getCatalogProperties().getSitesPropertyName());

The pContext.getParent().getPropertyValue() is out-of-the-box code upon which I don't have any control to modify.

Requirement:

I wanted to get the first default element out of it (always). However, I couldn't find a method get(index) like in an ArrayList.

Hence, right now, I am doing like this.

for (Iterator<String> it = siteIdSet.iterator(); it.hasNext();) {
    siteId = it.next();
    break;
}

Is there any (other) efficient way (short and better) of achieving this?

14 Answers

I just had the same problem and found your question here ...

This was my solution:

Set<Integer> mySetOfIntegers = new HashSet<Integer>();
/* ... there's at least one integer in the set ... */

Integer iFirstItemInSet = new ArrayList<Integer>(mySetOfIntegers).get(0);

Vector has some handy features:

Vector<String> siteIdVector = new Vector<>(siteIdSet);
String first = siteIdVector.firstElement();
String last = siteIdVector.lastElement();

But I do agree - this may have unintended consequences, since the underling set is not guaranteed to be ordered.

Related