I have a Set<Integer>
in my Java program which is guaranteed to be non-empty. I want to retrieve one of the Integers from this set. I do not care which Integer, I just need some Integer, deterministically or nondeterministically selected from the set, as long as it is in the set. What is the best way to do this?
Why not just take the first element?
return set.iterator().next();
If it's guaranteed to be non-empty, and you don't care which element you retrieve, this sounds about as simple as it gets.
There are a few ways. One is to call iterator(). Then call next()
on the Iterator.
Alternatively, you can call toArray then an element from that array (bound by the size of it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With