Java TreeSet tailSet() Method

A tailSet() method of TreeSet class returns the element present in the set, which is greater than or equal to fromElement. If the passed value is outside of the range, an IllegalArgumentException is thrown.

Syntax:

Specified by:

tailSet in interface NavigableSet<E> : It returns the element present in the set, which is greater than or equal to fromElement. If the passed value is outside of the range, an IllegalArgumentException is thrown.

Parameter:

fromElement - the Minimum endpoint of the returned set

Return:

It returns the set whose elements are greater than or equal to fromElement

Throws:

ClassCastException: Throws exception when typecasting is performed in the fromElements, and they are not compatible with elements in the set.

NullPointerException: Throws exception when Set elements are null.

IllegalArgumentException: Throws exception when set has a restricted range and fromElement is outside of range

Example 1

Output:

TreeSet: [4, 6, 9, 12, 18]
Elements of  TreeSet in object 1: [12, 18]
Elements of  TreeSet in object 2: [18]

Example 2

Output:

TreeSet: [1, 3, 6, 9, A, B, a, b]
Elements of  TreeSet in object 1: [A, B, a, b]
Elements of  TreeSet in object 2: [B, a, b]

Example 3

Output:

shristee  vishwakarma  Analyst
shweta    singh                Accountant
suman     chandra          Computer Engineer 
Elements of  TreeSet in object 1: [shweta    singh        Accountant, suman     chandra      Computer Engineer ]
Elements of  TreeSet in object 2: [suman     chandra      Computer Engineer ]

Java TreeSet tailSet() Method

The tailSet() method of TreeSet class returns the element present in the set, which is greater than or equal to fromElement. If the passed element is out of range, the IllegalArgumentException is thrown.

Syntax:

Parameter:

fromElement - the Minimum endpoint of the returned set

Return:

It returns the set whose elements are greater than or equal to fromElement

Throws:

ClassCastException: Throws exception when typecasting is performed in the fromElements, and they are not compatible with elements in the set.

NullPointerException: Throws exception when the Set elements are null.

IllegalArgumentException: Throws exception when the set has a restricted range and fromElement is outside of the range

Example 4

Output:

TreeSet: [4, 6, 9, 12, 18]
TreeSet: [12, 18]

Example 5

Output:

TreeSet: [1, 3, 6, 9, A, B, a, b]
Elemets of TreeSet: [a, b]
Elemets of TreeSet: [9, A, B, a, b]