java.util.Set specifies only methods that return all records (via Iterator or array).
Why is there no option to return any value from Set?
It has a lot of sense in the real life. For example, I have a bowl of strawberries and I want to take just one of them. I totally don’t care which one.
Why I can’t do the same in java?
This is not answerable. You’d have to ask the original designers of the Java collections framework.
One plausible reason is that methods with non-deterministic behavior tend to be problematic:
For hashtable-based set organizations, the behavior a “get some element” method is going to be non-deterministic, or at least difficult to determine / predict.
By the way, you can trivially get some element of a non-empty set as follows:
Getting a truly (pseudo-)random element is a bit more tricky / expensive because you can’t index the elements of a set. (You need to extract all of the set elements into an array …)
On revisiting this, I realized that there is another reason. It is simply that
Setis based on the mathematical notion of a set, and the elements of a set in mathematics have no order. It is simply meaningless to talk about the first element of a mathematical set.