Good way to get *any* value from a Java Set?

Jacob Marble picture Jacob Marble · Dec 3, 2012 · Viewed 45.5k times · Source

Given a simple Set<T>, what is a good way (fast, few lines of code) to get any value from the Set?

With a List, it's easy:

List<T> things = ...;
return things.get(0);

But, with a Set, there is no .get(...) method because Sets are not ordered.

Answer

Jacob Marble picture Jacob Marble · Dec 3, 2012

A Set<T> is an Iterable<T>, so iterating to the first element works:

Set<T> things = ...;
return things.iterator().next();

Guava has a method to do this, though the above snippet is likely better.