See the javadoc
of List
list.get(0);
or Set
set.iterator().next();
and check the size before using the above methods by invoking isEmpty()
!list_or_set.isEmpty()
Answer from stacker on Stack OverflowSee the javadoc
of List
list.get(0);
or Set
set.iterator().next();
and check the size before using the above methods by invoking isEmpty()
!list_or_set.isEmpty()
Collection c;
Iterator iter = c.iterator();
Object first = iter.next();
(This is the closest you'll get to having the "first" element of a Set. You should realize that it has absolutely no meaning for most implementations of Set. This may have meaning for LinkedHashSet and TreeSet, but not for HashSet.)
playersList.get(0)
Java has limited operator polymorphism. So you use the get() method on List objects, not the array index operator ([])
You have to access lists a little differently than arrays in Java. See the javadocs for the List interface for more information.
playersList.get(0)
However if you want to find the smallest element in playersList, you shouldn't sort it and then get the first element. This runs very slowly compared to just searching once through the list to find the smallest element.
For example:
int smallestIndex = 0;
for (int i = 1; i < playersList.size(); i++) {
if (playersList.get(i) < playersList.get(smallestIndex))
smallestIndex = i;
}
playersList.get(smallestIndex);
The above code will find the smallest element in O(n) instead of O(n log n) time.
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.
Iterables.get(yourC, indexYouWant)
Because really, if you're using Collections, you should be using Google Collections.