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


当前回答

Collection c;

Iterator iter = c.iterator();

Object first = iter.next();

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

其他回答

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

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

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

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

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)

这不是这个问题的确切答案,但如果对象应该排序SortedSet有一个first()方法:

SortedSet<String> sortedSet = new TreeSet<String>();
sortedSet.add("2");
sortedSet.add("1");
sortedSet.add("3");
String first = sortedSet.first(); //first="1"

排序对象必须实现Comparable接口(就像String那样)

Collection c;

Iterator iter = c.iterator();

Object first = iter.next();

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

请看javadoc

的列表

list.get(0);

或一组

set.iterator().next();

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

!list_or_set.isEmpty()