How to get first item from a java.util.Set?
This will return the first element
set.iterator().next();
From the Oracle docs:
As implied by its name, this interface models the mathematical set abstraction.
In Set Theory, "a "set" is a collection of distinct objects, considered as an object in its own right." - [Wikipedia - Set].
Mathematically, elements in sets are not individualised. Their only identity is derived from their presence in the set. Therefore, there is no point in getting the "first" element in a set, as conceptually such a task is illogical.
There may be no point to getting the "first" element from a set, but if all you need is to get one single object from a set (with no guarantees as to which object that is) you can do the following:
for(String aSiteId: siteIdSet) {
siteId = aSiteId;
break;
}
This is a slightly shorter way (than the method you posted) to get the "first" object of a Set
, however since an Iterator is still being created (under the hood) it does not grant any performance benefit.
Or, using Java8:
Object firstElement = set.stream().findFirst().get();
And then you can do stuff with it straight away:
set.stream().findFirst().ifPresent(<doStuffHere>);
Or, if you want to provide an alternative in case the element is missing (my example returns new default string):
set.stream().findFirst().orElse("Empty string");
You can even throw an exception if the first element is missing:
set.stream().findFirst().orElseThrow(() -> new MyElementMissingException("Ah, blip, nothing here!"));
Kudos to Alex Vulaj
for prompting me to provide more examples beyond the initial grabbing of the first element.