Java TreeSet Methods
TreeSet Methods
A TreeSet stores unique items, and keeps them sorted. The methods below use this order, for example to get the first item, the last item, or all items that are less than a given value.
Some methods use the type of the items in the set. This type is called T in the tables.
| Method | Description | Return Type |
|---|---|---|
| first() | Returns the first (lowest) item in the set | T |
| last() | Returns the last (highest) item in the set | T |
| floor() | Returns the greatest item that is less than or equal to the given value, or null if there is none | T |
| ceiling() | Returns the least item that is greater than or equal to the given value, or null if there is none | T |
| lower() | Returns the greatest item that is less than the given value, or null if there is none | T |
| higher() | Returns the least item that is greater than the given value, or null if there is none | T |
| headSet() | Returns a part of the set, with all items that are less than the given value | SortedSet|NavigableSet |
| tailSet() | Returns a part of the set, with all items that are greater than or equal to the given value | SortedSet|NavigableSet |
| subSet() | Returns a part of the set, with all items between two given values | SortedSet|NavigableSet |
| pollFirst() | Removes and returns the first (lowest) item, or null if the set is empty | T |
| pollLast() | Removes and returns the last (highest) item, or null if the set is empty | T |
| descendingSet() | Returns the set with the items in reverse (descending) order | NavigableSet |
Methods Shared with HashSet
A TreeSet also has the methods below. They work the same way as in a HashSet, so the links go to the HashSet reference pages. The difference is that a TreeSet keeps the items sorted, so methods like iterator() and toArray() give you the items in sorted order. A TreeSet also does not allow null as an item.
| Method | Description | Return Type |
|---|---|---|
| add() | Adds an item to the set, if it is not already there | boolean |
| addAll() | Adds all items from a collection to the set | boolean |
| clear() | Removes all items from the set | void |
| clone() | Creates a copy of the set | Object |
| contains() | Checks if an item exists in the set | boolean |
| isEmpty() | Checks if the set is empty | boolean |
| iterator() | Returns an Iterator object, to loop through the items of the set | Iterator |
| remove() | Removes an item from the set | boolean |
| removeAll() | Removes all items that are also in a given collection | boolean |
| size() | Returns the number of items in the set | int |
| spliterator() | Returns a Spliterator object for the set | Spliterator |
| toArray() | Returns an array with all items of the set | Object[] |