Java: Get first item from a collection

后端 未结 12 1128
说谎
说谎 2020-11-29 17:08

If I have a collection, such as Collection strs, how can I get the first item out? I could just call an Iterator, take its first

12条回答
  •  臣服心动
    2020-11-29 17:39

    Guava provides an onlyElement Collector, but only use it if you expect the collection to have exactly one element.

    Collection stringCollection = ...;
    String string = collection.stream().collect(MoreCollectors.onlyElement())
    

    If you are unsure of how many elements there are, use findFirst.

    Optional optionalString = collection.stream().findFirst();
    

提交回复
热议问题