Java: Get first item from a collection

后端 未结 12 1087
说谎
说谎 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:13

    There is no such a thing as "first" item in a Collection because it is .. well simply a collection.

    From the Java doc's Collection.iterator() method:

    There are no guarantees concerning the order in which the elements are returned...

    So you can't.

    If you use another interface such as List, you can do the following:

    String first = strs.get(0);
    

    But directly from a Collection this is not possible.

    0 讨论(0)
  • 2020-11-29 17:14

    It sounds like your Collection wants to be List-like, so I'd suggest:

    List<String> myList = new ArrayList<String>();
    ...
    String first = myList.get(0);
    
    0 讨论(0)
  • 2020-11-29 17:15

    Iterables.get(yourC, indexYouWant)

    Because really, if you're using Collections, you should be using Google Collections.

    0 讨论(0)
  • 2020-11-29 17:19

    You can do a casting. For example, if exists one method with this definition, and you know that this method is returning a List:

    Collection<String> getStrings();
    

    And after invoke it, you need the first element, you can do it like this:

    List<String> listString = (List) getStrings();
    String firstElement = (listString.isEmpty() ? null : listString.get(0));
    
    0 讨论(0)
  • 2020-11-29 17:22

    It totally depends upon which implementation you have used, whether arraylist linkedlist, or other implementations of set.

    if it is set then you can directly get the first element , their can be trick loop over the collection , create a variable of value 1 and get value when flag value is 1 after that break that loop.

    if it is list's implementation then it is easy by defining index number.

    0 讨论(0)
  • 2020-11-29 17:23

    You could do this:

    String strz[] = strs.toArray(String[strs.size()]);
    String theFirstOne = strz[0];
    

    The javadoc for Collection gives the following caveat wrt ordering of the elements of the array:

    If this collection makes any guarantees as to what order its elements are returned by its iterator, this method must return the elements in the same order.

    0 讨论(0)
提交回复
热议问题