Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an element from a Set?

Tags:

java

set

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?

like image 695
Void Star Avatar asked Sep 19 '25 00:09

Void Star


2 Answers

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.

like image 68
Jon Skeet Avatar answered Sep 21 '25 13:09

Jon Skeet


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

like image 21
Daniel Kaplan Avatar answered Sep 21 '25 13:09

Daniel Kaplan