Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Get first item from a collection

If I have a collection, such as Collection<String> strs, how can I get the first item out? I could just call an Iterator, take its first next(), then throw the Iterator away. Is there a less wasteful way to do it?

like image 247
Nick Heiner Avatar asked Nov 04 '09 02:11

Nick Heiner


People also ask

How do I get the first item in a list?

Get the first element of ArrayList with use of get(index) method by passing index = 0.

How do I iterate through collections?

There are three common ways to iterate through a Collection in Java using either while(), for() or for-each(). While each technique will produce more or less the same results, the for-each construct is the most elegant and easy to read and write.

Which collection type is faster if you have to find an item?

If you need fast add and removal of elements, use LinkedList (but it has a very poor seeking performance).


2 Answers

Looks like that is the best way to do it:

String first = strs.iterator().next(); 

Great question... At first, it seems like an oversight for the Collection interface.

Note that "first" won't always return the first thing you put in the collection, and may only make sense for ordered collections. Maybe that is why there isn't a get(item) call, since the order isn't necessarily preserved.

While it might seem a bit wasteful, it might not be as bad as you think. The Iterator really just contains indexing information into the collection, not a usually a copy of the entire collection. Invoking this method does instantiate the Iterator object, but that is really the only overhead (not like copying all the elements).

For example, looking at the type returned by the ArrayList<String>.iterator() method, we see that it is ArrayList::Itr. This is an internal class that just accesses the elements of the list directly, rather than copying them.

Just be sure you check the return of iterator() since it may be empty or null depending on the implementation.

like image 156
jheddings Avatar answered Oct 04 '22 16:10

jheddings


Iterables.get(yourC, indexYouWant)

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

like image 30
Carl Avatar answered Oct 04 '22 17:10

Carl