我想知道我是否能得到一个列表或集合的第一个元素。使用哪种方法?


当前回答

请看javadoc

的列表

list.get(0);

或一组

set.iterator().next();

并在使用上述方法之前通过调用isEmpty()检查大小

!list_or_set.isEmpty()

其他回答

Collection c;

Iterator iter = c.iterator();

Object first = iter.next();

(这是最接近Set的“第一个”元素。您应该意识到,对于Set的大多数实现来说,它绝对没有任何意义。这可能对LinkedHashSet和TreeSet有意义,但对HashSet没有意义。)

可以使用get(index)方法访问List中的元素。

根据定义,集合只是包含元素,没有特定的顺序。因此,您无法获得“first”元素,但可以使用迭代器(使用for每个循环)遍历它,或使用toArray()方法将其转换为数组。

我很惊讶没有人提出番石榴解决方案:

com.google.common.collect.Iterables.get(collection, 0)
// or
com.google.common.collect.Iterables.get(collection, 0, defaultValue)
// or
com.google.common.collect.Iterables.getFirst(collection, defaultValue)

或者如果你想要单个元素:

com.google.common.collect.Iterables.getOnlyElement(collection, defaultValue)
// or
com.google.common.collect.Iterables.getOnlyElement(collection)

在Java >=8中,你也可以使用流式API:

Optional<String> first = set.stream().findFirst();

(如果Set/List可能为空,则有用。)

请看javadoc

的列表

list.get(0);

或一组

set.iterator().next();

并在使用上述方法之前通过调用isEmpty()检查大小

!list_or_set.isEmpty()