1. Introduction
TreeSet is a part of the Java Collections Framework and is implemented as a red-black tree, which means it stores elements in a sorted manner. This sorting can be based on their natural order or a custom order defined through a Comparator. Accessing elements in a TreeSet is straightforward. In this blog post, we will discuss various methods to access elements from a TreeSet.
2. Program Steps
1. Import necessary packages.
2. Create and populate a TreeSet with some elements.
3. Access the first and last elements of the TreeSet using first() and last() methods.
4. Retrieve and print elements using various methods like higher(), lower(), ceiling(), and floor().
3. Code Program
import java.util.TreeSet;
public class AccessTreeSetElements {
public static void main(String[] args) {
// Step 2: Create and populate a TreeSet with some elements
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);
// Step 3: Access the first and last elements
System.out.println("First element: " + numbers.first());
System.out.println("Last element: " + numbers.last());
// Step 4: Retrieve and print elements using various methods
System.out.println("Element higher than 30: " + numbers.higher(30));
System.out.println("Element lower than 30: " + numbers.lower(30));
System.out.println("Element ceiling to 25: " + numbers.ceiling(25));
System.out.println("Element floor to 25: " + numbers.floor(25));
}
}
Output:
First element: 10 Last element: 50 Element higher than 30: 40 Element lower than 30: 20 Element ceiling to 25: 30 Element floor to 25: 20
4. Step By Step Explanation
Step 1: We start by importing the required package for TreeSet.
Step 2: We initialize a TreeSet named numbers and populate it with some integer values.
Step 3: The first() method returns the first (lowest) element currently in the TreeSet, and the last() method returns the last (highest) element. Both of these are demonstrated.
Step 4: We then use various methods to retrieve elements:
– higher(E e): Returns the least element greater than the given element, or null if there is no such element.
– lower(E e): Returns the greatest element less than the given element, or null if there is no such element.
– ceiling(E e): Returns the least element greater than or equal to the given element, or null if there is no such element.
– floor(E e): Returns the greatest element less than or equal to the given element, or null if there is no such element.
These methods help in accessing specific elements from a TreeSet based on certain conditions or relative positions.