Get subset from TreeSet in Java

In this tutorial, we will learn how to Get subset from TreeSet in Java.

TreeSet in Java extends AbstractSet and implements the NavigableSet interface. It creates a collection that uses a tree for storage. The objects are stored in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly. TreeSet is similar to HashSet, the difference is that TreeSet sorts the elements in ascending order and doesn’t allow null elements.

TreeSet class in Java provides subSet() method to get subset from TreeSet. The syntax of subSet() method is:

Syntax of subSet() method:

fromElement – index(inclusive) from which subset to be obtained
toElement – end index(exclusive)

returns a subset whose elements range from fromElement inclusive to toElement exclusive

ClassCastException – if fromElement and toElement cannot be compared to one another using this set’s comparator (or, if the set has no comparator, using natural ordering). Implementations may, but are not required to, throw this exception if fromElement or toElement cannot be compared to elements currently in the set.
NullPointerException – if fromElement or toElement is null and this set uses natural ordering, or its comparator does not permit null elements
IllegalArgumentException – if fromElement is greater than toElement; or if this set itself has a restricted range, and fromElement or toElement lies outside the bounds of the range




Related posts

Leave a Comment