问题描述
给定一个简单的 Set<T>,从 Set 获取 any 值的好方法是什么(快速,几行代码)代码>?
Given a simple Set<T>, what is a good way (fast, few lines of code) to get any value from the Set?
有了List,很简单:
List<T> things = ...; return things.get(0);
但是,对于 Set,没有 .get(...) 方法,因为 Set 没有顺序.
But, with a Set, there is no .get(...) method because Sets are not ordered.
推荐答案
一个 Set
A Set<T> is an Iterable<T>, so iterating to the first element works:
Set<T> things = ...; return things.iterator().next();
Guava 有 一种方法 来做到这一点,虽然上面的代码片段 可能更好.
Guava has a method to do this, though the above snippet is likely better.