Fetching an element from a TreeSet

The following methods can be used to fetch elements from a TreeSet.

Fetching the first element

We can fetch the first element in the TreeSet using the first() method. If the TreeSet is empty, then NoSuchElementException is thrown.

Fetching the last element

We can fetch the last element in the TreeSet using the last() method. If the TreeSet is empty, then NoSuchElementException is thrown.

Fetching the subset of elements

We can use the subSet(E fromElement, E toElement) method to fetch a subset of TreeSet within a given range. This method will return the elements ranging from fromElement to toElement. Note that fromElement is inclusive and toElement is exclusive.

Fetching elements that are smaller than the given element

The headSet(E toElement) method returns all the elements that are smaller than the provided element. The toElement is not inclusive.

Fetching elements that are greater than the given element

The tailSet(E fromElement) method returns all the elements which are greater than the provided element. The fromElement is not inclusive.

Get hands-on with 1400+ tech skills courses.