[java] How to get the first element of the List or Set?

I'd like to know if I can get the first element of a list or set. Which method to use?

This question is related to java list collections set

The answer is


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


This is not an exact answer to this question, but in case the objects should be sorted SortedSet has a first() method:

SortedSet<String> sortedSet = new TreeSet<String>();
sortedSet.add("2");
sortedSet.add("1");
sortedSet.add("3");
String first = sortedSet.first(); //first="1"

The sorted objects must implement the Comparable interface (like String does)


You can use the get(index) method to access an element from a List.

Sets, by definition, simply contain elements and have no particular order. Therefore, there is no "first" element you can get, but it is possible to iterate through it using iterator (using the for each loop) or convert it to an array using the toArray() method.


Let's assume that you have a List<String> strings that you want the first item from.

There are several ways to do that:

Java (pre-8):

String firstElement = null;
if (!strings.isEmpty() && strings.size() > 0) {
    firstElement = strings.get(0);
}

Java 8:

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

Guava

String firstElement = Iterables.getFirst(strings, null);

Apache commons (4+)

String firstElement = (String) IteratorUtils.get(strings, 0);

Apache commons (before 4)

String firstElement = (String) CollectionUtils.get(strings, 0);

Followed by or encapsulated within the appropriate checks or try-catch blocks.

Kotlin:

In Kotlin both Arrays and most of the Collections (eg: List) have a first method call. So your code would look something like this

for a List:

val stringsList: List<String?> = listOf("a", "b", null)
val first: String? = stringsList.first()

for an Array:

val stringArray: Array<String?> = arrayOf("a", "b", null)
val first: String? = stringArray.first()

Followed by or encapsulated within the appropriate checks or try-catch blocks.

Kotlin also includes safer ways to do that for kotlin.collections, for example firstOrNull or getOrElse, or getOrDefault when using JRE8


and further

Set<String> set = new TreeSet<>();
    set.add("2");
    set.add("1");
    set.add("3");
    String first = set.stream().findFirst().get();

This will help you retrieve the first element of the list or set. Given that the set or list is not empty (get() on empty optional will throw java.util.NoSuchElementException)

orElse() can be used as: (this is just a work around - not recommended)

String first = set.stream().findFirst().orElse("");
set.removeIf(String::isEmpty);

Below is the appropriate approach :

Optional<String> firstString = set.stream().findFirst();
if(firstString.isPresent()){
    String first = firstString.get();
}

Similarly first element of the list can be retrieved.

Hope this helps.


Set

set.toArray()[0];

List

list.get(0);

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

In Java >=8 you could also use the Streaming API:

Optional<String> first = set.stream().findFirst();

(Useful if the Set/List may be empty.)


I'm surprised that nobody suggested guava solution yet:

com.google.common.collect.Iterables.get(collection, 0)
// or
com.google.common.collect.Iterables.get(collection, 0, defaultValue)
// or
com.google.common.collect.Iterables.getFirst(collection, defaultValue)

or if you expect single element:

com.google.common.collect.Iterables.getOnlyElement(collection, defaultValue)
// or
com.google.common.collect.Iterables.getOnlyElement(collection)

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 list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

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 set

java, get set methods golang why don't we have a set datastructure Simplest way to merge ES6 Maps/Sets? Swift Set to Array JavaScript Array to Set How to sort a HashSet? Python Set Comprehension How to get first item from a java.util.Set? Getting the difference between two sets Python convert set to string and vice versa