[java] 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?

This question is related to java collections iterable

The answer is


Iterables.get(yourC, indexYouWant)

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


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

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

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

Optional<String> optionalString = collection.stream().findFirst();

In Java 8 you have some many operators to use, for instance limit

     /**
 * Operator that limit the total number of items emitted through the pipeline
 * Shall print
 * [1]
 * @throws InterruptedException
 */
@Test
public void limitStream() throws InterruptedException {
    List<Integer> list = Arrays.asList(1, 2, 3, 1, 4, 2, 3)
                               .stream()
                               .limit(1)
                               .collect(toList());
    System.out.println(list);
}

Functional way:

public static <T> Optional<T> findFirst(List<T> result) {
    return Optional.ofNullable(result)
            .map(List::stream)
            .flatMap(Stream::findFirst);
}

above code snippet preserve from NullPointerException and IndexOutOfBoundsException


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.


If you know that the collection is a queue then you can cast the collection to a queue and get it easily.

There are several structures you can use to get the order, but you will need to cast to it.


In java 8:

Optional<String> firstElement = collection.stream().findFirst();

For older versions of java, there is a getFirst method in Guava Iterables:

Iterables.getFirst(iterable, defaultValue)

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);

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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?

Examples related to iterable

Convert Iterable to Stream using Java 8 JDK Python - TypeError: 'int' object is not iterable Get size of an Iterable in Java Convert Java Array to Iterable What exactly are iterator, iterable, and iteration? What is the difference between iterator and iterable and how to use them? Easy way to convert Iterable to Collection How do I add the contents of an iterable to a set? In Python, how do I determine if an object is iterable? Java: Get first item from a collection