如果我有一个集合,如集合<String> strs,我怎么能得到第一项?我可以调用一个迭代器,取它的第一个next(),然后丢弃迭代器。有没有更少浪费的方法呢?


当前回答

Iterables。get (indexYouWant yourC)

因为实际上,如果你使用集合,你应该使用谷歌集合。

其他回答

这完全取决于你使用的是哪种实现,是arraylist linkedlist,还是set的其他实现。

如果它被设置了,那么你可以直接获得第一个元素,它们可以在集合上进行诡计循环,创建一个值为1的变量,当标志值为1时获得值,然后打破循环。

如果是列表的实现,那么通过定义索引号很容易。

在Java 8中,你有很多操作符可以使用,比如limit

     /**
 * Operator that limit the total number of items emitted through the pipeline
 * Shall print
 * [1]
 * @throws InterruptedException
 */
@Test
public void limitStream() throws InterruptedException {
    List<Integer> list = Arrays.asList(1, 2, 3, 1, 4, 2, 3)
                               .stream()
                               .limit(1)
                               .collect(toList());
    System.out.println(list);
}

听起来你的Collection想要像list一样,所以我建议:

List<String> myList = new ArrayList<String>();
...
String first = myList.get(0);

如果知道集合是队列,则可以将集合强制转换为队列并轻松获取它。

您可以使用几个结构来获得订单,但需要对其进行强制转换。

在java 8中:

Optional<String> firstElement = collection.stream().findFirst();

对于旧版本的java,在Guava Iterables中有一个getFirst方法:

Iterables.getFirst(iterable, defaultValue)