从Java集获取* any *值的好方法? [英] Good way to get *any* value from a Java Set?
本文介绍了从Java集获取* any *值的好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个简单的 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
s不排序.>
But, with a Set
, there is no .get(...)
method because Set
s are not ordered.
推荐答案
Set< T>
是 Iterable< T>
,因此迭代到第一个元素是可行的:
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.
这篇关于从Java集获取* any *值的好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文