If I have a collection, such as Collection
, how can I get the first item out? I could just call an Iterator
, take its first
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.
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);
Iterables.get(yourC, indexYouWant)
Because really, if you're using Collections, you should be using Google Collections.
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));
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.
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.