Java
|
Initial TreeSet [A, B, For, Geek, Geeks, Z]
After removing element [A, For, Geek, Geeks, Z]
After removing first [For, Geek, Geeks, Z]
After removing last [For, Geek, Geeks]
Operation 4: Iterating through the TreeSet
There are various ways to iterate through the TreeSet. The most famous one is to use the enhanced for loop. and geeks mostly you would be iterating the elements with this approach while practicing questions over TreeSet as this is most frequently used when it comes to tree, maps, and graphs problems.
Example
TreeSet contains()
The contains() method is used to check if a given element is present in a given TreeSet. If the element is found, it returns true, otherwise false.
Let’s see the contains() in action:
@Test
public void whenCheckingForElement_shouldSearchForElement() {
Set
treeSetContains = new TreeSet<>();
treeSetContains.add("String Added");
assertTrue(treeSetContains.contains("String Added"));
}
Methods for Navigation
Since the
TreeSet
class implements
NavigableSet
, it provides various methods to navigate over the elements of the tree set.
first() and last() Methods
-
first()
– returns the first element of the set -
last()
– returns the last element of the set
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet
numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(6); System.out.println("TreeSet: " + numbers); // Using the first() method int first = numbers.first(); System.out.println("First Number: " + first); // Using the last() method int last = numbers.last(); System.out.println("Last Number: " + last); } }
Output
TreeSet: [2, 5, 6] First Number: 2 Last Number: 6
ceiling(), floor(), higher() and lower() Methods
-
higher(element) – Returns the lowest element among those elements that are greater than the specified
element
. -
lower(element) – Returns the greatest element among those elements that are less than the specified
element
. -
ceiling(element) – Returns the lowest element among those elements that are greater than the specified element. If the element passed exists in a tree set, it returns the
element
passed as an argument. -
floor(element) – Returns the greatest element among those elements that are less than the specified
element
. If the element passed exists in a tree set, it returns the
element
passed as an argument.
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet
numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(4); numbers.add(6); System.out.println("TreeSet: " + numbers); // Using higher() System.out.println("Using higher: " + numbers.higher(4)); // Using lower() System.out.println("Using lower: " + numbers.lower(4)); // Using ceiling() System.out.println("Using ceiling: " + numbers.ceiling(4)); // Using floor() System.out.println("Using floor: " + numbers.floor(3)); } }
Output
TreeSet: [2, 4, 5, 6] Using higher: 5 Using lower: 2 Using ceiling: 4 Using floor: 2
pollfirst() and pollLast() Methods
-
pollFirst()
– returns and removes the first element from the set -
pollLast()
– returns and removes the last element from the set
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet
numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(4); numbers.add(6); System.out.println("TreeSet: " + numbers); // Using pollFirst() System.out.println("Removed First Element: " + numbers.pollFirst()); // Using pollLast() System.out.println("Removed Last Element: " + numbers.pollLast()); System.out.println("New TreeSet: " + numbers); } }
Output
TreeSet: [2, 4, 5, 6] Removed First Element: 2 Removed Last Element: 6 New TreeSet: [4, 5]
headSet(), tailSet() and subSet() Methods
headSet(element, booleanValue)
The
headSet()
method returns all the elements of a tree set before the specified element (which is passed as an argument).
The booleanValue parameter is optional. Its default value is
false
.
If
true
is passed as a booleanValue, the method returns all the elements before the specified element including the specified element.
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet
numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(4); numbers.add(6); System.out.println("TreeSet: " + numbers); // Using headSet() with default boolean value System.out.println("Using headSet without boolean value: " + numbers.headSet(5)); // Using headSet() with specified boolean value System.out.println("Using headSet with boolean value: " + numbers.headSet(5, true)); } }
Output
TreeSet: [2, 4, 5, 6] Using headSet without boolean value: [2, 4] Using headSet with boolean value: [2, 4, 5]
tailSet(element, booleanValue)
The
tailSet()
method returns all the elements of a tree set after the specified element (which is passed as a parameter) including the specified element.
The booleanValue parameter is optional. Its default value is
true
.
If
false
is passed as a booleanValue, the method returns all the elements after the specified element without including the specified element.
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet
numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(4); numbers.add(6); System.out.println("TreeSet: " + numbers); // Using tailSet() with default boolean value System.out.println("Using tailSet without boolean value: " + numbers.tailSet(4)); // Using tailSet() with specified boolean value System.out.println("Using tailSet with boolean value: " + numbers.tailSet(4, false)); } }
Output
TreeSet: [2, 4, 5, 6] Using tailSet without boolean value: [4, 5, 6] Using tailSet with boolean value: [5, 6]
subSet(e1, bv1, e2, bv2)
The
subSet()
method returns all the elements between e1 and e2 including e1.
The bv1 and bv2 are optional parameters. The default value of bv1 is
true
, and the default value of bv2 is
false
.
If
false
is passed as bv1, the method returns all the elements between e1 and e2 without including
e1
.
If
true
is passed as bv2, the method returns all the elements between e1 and e2, including e1.
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet
numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(4); numbers.add(6); System.out.println("TreeSet: " + numbers); // Using subSet() with default boolean value System.out.println("Using subSet without boolean value: " + numbers.subSet(4, 6)); // Using subSet() with specified boolean value System.out.println("Using subSet with boolean value: " + numbers.subSet(4, false, 6, true)); } }
Output
TreeSet: [2, 4, 5, 6] Using subSet without boolean value: [4, 5] Using subSet with boolean value: [5, 6]
Java
|
Initial TreeSet [A, B, For, Geek, Geeks, Z]
After removing element [A, For, Geek, Geeks, Z]
After removing first [For, Geek, Geeks, Z]
After removing last [For, Geek, Geeks]
Operation 4: Iterating through the TreeSet
There are various ways to iterate through the TreeSet. The most famous one is to use the enhanced for loop. and geeks mostly you would be iterating the elements with this approach while practicing questions over TreeSet as this is most frequently used when it comes to tree, maps, and graphs problems.
Example
Java
|
A, B, For, Geek, Geeks, Z,
Features of a TreeSet:
- TreeSet implements the SortedSet interface. So, duplicate values are not allowed.
- Objects in a TreeSet are stored in a sorted and ascending order.
- TreeSet does not preserve the insertion order of elements but elements are sorted by keys.
- If we are depending on the default natural sorting order, the objects that are being inserted into the tree should be homogeneous and comparable. TreeSet does not allow the insertion of heterogeneous objects. It will throw a classCastException at Runtime if we try to add heterogeneous objects.
- The TreeSet can only accept generic types which are comparable.For example, the StringBuffer class implements the Comparable interface
Java
|
TreeSet contains:
contribute
for
geeks
practice
Example 2:
Example
The following program illustrates several of the methods supported by this collection −
import java.util.*; public class TreeSetDemo { public static void main(String args[]) { // Create a tree set TreeSet ts = new TreeSet(); // Add elements to the tree set ts.add(“C”); ts.add(“A”); ts.add(“B”); ts.add(“E”); ts.add(“F”); ts.add(“D”); System.out.println(ts); } }
This will produce the following result −
Java
|
[For, Geek, Geeks]
Operation 2: Accessing the Elements
After adding the elements, if we wish to access the elements, we can use inbuilt methods like contains(), first(), last(), etc.
Example
Access TreeSet Elements
To access the elements of a tree set, we can use the
iterator()
method. In order to use this method, we must import
java.util.Iterator
package. For example,
import java.util.TreeSet; import java.util.Iterator; class Main { public static void main(String[] args) { TreeSet
numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(6); System.out.println("TreeSet: " + numbers); // Calling iterator() method Iterator
iterate = numbers.iterator(); System.out.print("TreeSet using Iterator: "); // Accessing elements while(iterate.hasNext()) { System.out.print(iterate.next()); System.out.print(", "); } } }
Output
TreeSet: [2, 5, 6] TreeSet using Iterator: 2, 5, 6,
TreeSet với thiết lập so sánh tùy chỉnh
Ví dụ sau cho thấy cách tạo ra một TreeSet bằng thiết lập so sánh tùy chỉnh. Đó là sắp xếp tên theo thứ tự A-B.
import java.util.Comparator; import java.util.SortedSet; import java.util.TreeSet; public class TreeSetCaseInsensitiveExample { public static void main(String[] args) { // Creating a TreeSet with a custom Comparator (Case Insensitive Order) SortedSet
fruits = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); /* The above TreeSet with the custom Comparator is the concise form of the following: SortedSet
fruits = new TreeSet<>(new Comparator
() { @Override public int compare(String s1, String s2) { return s1.compareToIgnoreCase(s2); } }); */ // Adding new elements to a TreeSet fruits.add("Banana"); fruits.add("Apple"); fruits.add("Pineapple"); fruits.add("Orange"); System.out.println("Fruits Set : " + fruits); // Now, lowercase elements will also be considered as duplicates fruits.add("banana"); System.out.println("After adding \"banana\" : " + fruits); } }
# Output Fruits Set : [Apple, Banana, Orange, Pineapple] After adding "banana" : [Apple, Banana, Orange, Pineapple]
Java
|
HashSet contains:
practice
geeks
for
contribute
Example 2:
Truy cập các phần tử của một TreeSet
Ví dụ sau đây thực hiện các việc sau :
- Xác định size của một TreeSet.
- Kiểm tra xem một phần tử có tồn tại trong TreeSet hay không.
- Tìm phần tử đầu tiên của một TreeSet.
- Tìm phần tử cuối cùng của một TreeSet.
- Tìm phần tử lớn hơn phần tử đã cho trong TreeSet.
- Tìm phần tử nhỏ hơn phần tử đã cho trong TreeSet.
import java.util.TreeSet; public class AccessTreeSetElementsExample { public static void main(String[] args) { TreeSet
students = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); students.add("Julia"); students.add("Robert"); students.add("Mark"); students.add("Steven"); System.out.println("Students TreeSet : " + students); // Finding the size of a TreeSet System.out.println("Number of elements in the TreeSet : " + students.size()); // Check if an element exists in the TreeSet String name = "Julia"; if(students.contains(name)) { System.out.println("TreeSet contains the element : " + name); } else { System.out.println("TreeSet does not contain the element : " + name); } // Navigating through the TreeSet System.out.println("First element : " + students.first()); System.out.println("Last element : " + students.last()); name = "Robert"; System.out.println("Element just greater than " + name + " : " + students.higher(name)); System.out.println("Element just lower than " + name + " : " + students.lower(name)); } }
# Output Students TreeSet : [Julia, Mark, Robert, Steven] Number of elements in the TreeSet : 4 TreeSet contains the element : Julia First element : Julia Last element : Steven Element just greater than Robert : Steven Element just lower than Robert : Mark
TreeSet với tùy chỉnh Comparator (Thứ tự giảm dần)
Ví dụ dưới đây minh họa cách tạo một TreeSet bằng một bộ so sánh tùy chỉnh, sắp xếp các phần tử theo thứ tự giảm dần.
import java.util.Comparator; import java.util.SortedSet; import java.util.TreeSet; public class TreeSetDescendingOrderExample { public static void main(String[] args) { // Creating a TreeSet with a custom Comparator (Descending Order) SortedSet
fruits = new TreeSet<>(Comparator.reverseOrder()); /* The above TreeSet with the custom Comparator is the concise form of the following: SortedSet
fruits = new TreeSet<>(new Comparator
() { @Override public int compare(String s1, String s2) { return s2.compareTo(s1); } }); */ // Adding new elements to a TreeSet fruits.add("Banana"); fruits.add("Apple"); fruits.add("Pineapple"); fruits.add("Orange"); System.out.println("Fruits Set : " + fruits); } }
# Output Fruits Set : [Pineapple, Orange, Banana, Apple]
Java Error & Exceptions
- Java – Exceptions
- Java – try-catch Block
- Java – try-with-resources
- Java – Multi-catch Block
- Java – Nested try Block
- Java – Finally Block
- Java – throw Exception
- Java – Exception Propagation
- Java – Built-in Exceptions
- Java – Custom Exception
TreeSet add()
The add() method, as expected, can be used for adding elements to a TreeSet. If an element was added, the method returns true, otherwise – false.
The contract of the method states that an element will be added only when the same isn’t already present in the Set.
Let’s add an element to a TreeSet:
@Test
public void whenAddingElement_shouldAddElement() {
Set
treeSet = new TreeSet<>();
assertTrue(treeSet.add("String Added"));
}
The add method is extremely important as the implementation details of the method illustrate how the TreeSet works internally, how it leverages the TreeMap’s put method to store the elements:
public boolean add(E e) {
return m.put(e, PRESENT) == null;
}
The variable m refers to an internal backing TreeMap (note that TreeMap implements NavigateableMap):
private transient NavigableMap
m;
Therefore, the TreeSet internally depends on a backing NavigableMap which gets initialized with an instance of TreeMap when an instance of the TreeSet is created:
public TreeSet() {
this(new TreeMap
());
}
More about this can be found in this article.
E- the type of elements maintained by this set
public class TreeSet
extends AbstractSet
implements NavigableSet
, Cloneable, Serializable
NavigableSetimplementation based on a
TreeMap. The elements are ordered using their natural ordering, or by a
Comparatorprovided at set creation time, depending on which constructor is used.
This implementation provides guaranteed log(n) time cost for the basic
operations (
add
,
remove
and
contains
).
Note that the ordering maintained by a set (whether or not an explicit
comparator is provided) must be consistent with equals if it is to
correctly implement the
Set
interface. (See
Comparable
or
Comparator
for a precise definition of consistent with
equals.) This is so because the
Set
interface is defined in
terms of the
equals
operation, but a
TreeSet
instance
performs all element comparisons using its
compareTo
(or
compare
) method, so two elements that are deemed equal by this method
are, from the standpoint of the set, equal. The behavior of a set
is well-defined even if its ordering is inconsistent with equals; it
just fails to obey the general contract of the
Set
interface.
Note that this implementation is not synchronized.
If multiple threads access a tree set concurrently, and at least one
of the threads modifies the set, it must be synchronized
externally. This is typically accomplished by synchronizing on some
object that naturally encapsulates the set.
If no such object exists, the set should be “wrapped” using the
Collections.synchronizedSortedSet
method. This is best done at creation time, to prevent accidental
unsynchronized access to the set:
SortedSet s = Collections.synchronizedSortedSet(new TreeSet(…));
The iterators returned by this class’s
iterator
method are
fail-fast: if the set is modified at any time after the iterator is
created, in any way except through the iterator’s own
remove
method, the iterator will throw a
ConcurrentModificationException
.
Thus, in the face of concurrent modification, the iterator fails quickly
and cleanly, rather than risking arbitrary, non-deterministic behavior at
an undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed
as it is, generally speaking, impossible to make any hard guarantees in the
presence of unsynchronized concurrent modification. Fail-fast iterators
throw
ConcurrentModificationException
on a best-effort basis.
Therefore, it would be wrong to write a program that depended on this
exception for its correctness: the fail-fast behavior of iterators
should be used only to detect bugs.
This class is a member of the Java Collections Framework.
Collection,
Set,
HashSet,
Comparable,
Comparator,
TreeMap, Serialized Form
Constructor and Description |
Constructs a new, empty tree set, sorted according to the natural ordering of its elements. |
Constructs a new tree set containing the elements in the specified collection, sorted according to the natural ordering of its elements. |
Constructs a new, empty tree set, sorted according to the specified comparator. |
Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set. |
Modifier and Type | Method and Description |
Adds the specified element to this set if it is not already present. |
|
Adds all of the elements in the specified collection to this set. |
|
Returns the least element in this set greater than or equal to the given element, or |
|
Removes all of the elements from this set. |
|
Returns a shallow copy of this |
|
Returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements. |
|
Returns |
|
Returns an iterator over the elements in this set in descending order. |
|
Returns a reverse order view of the elements contained in this set. |
|
Returns the first (lowest) element currently in this set. |
|
Returns the greatest element in this set less than or equal to the given element, or |
|
Returns a view of the portion of this set whose elements are strictly less than toElement. |
|
Returns a view of the portion of this set whose elements are less than (or equal to, if |
|
Returns the least element in this set strictly greater than the given element, or |
|
Returns |
|
Returns an iterator over the elements in this set in ascending order. |
|
Returns the last (highest) element currently in this set. |
|
Returns the greatest element in this set strictly less than the given element, or |
|
Retrieves and removes the first (lowest) element, or returns |
|
Retrieves and removes the last (highest) element, or returns |
|
Removes the specified element from this set if it is present. |
|
Returns the number of elements in this set (its cardinality). |
|
Creates a late-binding and fail-fast |
|
Returns a view of the portion of this set whose elements range from |
|
Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive. |
|
Returns a view of the portion of this set whose elements are greater than or equal to fromElement. |
|
Returns a view of the portion of this set whose elements are greater than (or equal to, if |
equals, hashCode, removeAll
containsAll, retainAll, toArray, toArray, toString
finalize, getClass, notify, notifyAll, wait, wait, wait
containsAll, equals, hashCode, removeAll, retainAll, toArray, toArray
parallelStream, removeIf, stream
public TreeSet()
Comparableinterface. Furthermore, all such elements must be mutually comparable:
e1.compareTo(e2)must not throw a
ClassCastExceptionfor any elements
e1and
e2in the set. If the user attempts to add an element to the set that violates this constraint (for example, the user attempts to add a string element to a set whose elements are integers), the
addcall will throw a
ClassCastException.
public TreeSet(Comparator
super E>
comparator)
comparator.compare(e1, e2)must not throw a
ClassCastExceptionfor any elements
e1and
e2in the set. If the user attempts to add an element to the set that violates this constraint, the
addcall will throw a
ClassCastException.
comparator- the comparator that will be used to order this set. If
null, the natural ordering of the elements will be used.
public TreeSet(Collection
extends E>
c)
Comparableinterface. Furthermore, all such elements must be mutually comparable:
e1.compareTo(e2)must not throw a
ClassCastExceptionfor any elements
e1and
e2in the set.
c- collection whose elements will comprise the new set
ClassCastException- if the elements in
care not
Comparable, or are not mutually comparable
NullPointerException- if the specified collection is null
public TreeSet(SortedSet
s)
s- sorted set whose elements will comprise the new set
NullPointerException- if the specified sorted set is null
public Iterator
iterator()
iteratorin interface
Iterable
iteratorin interface
Collection
iteratorin interface
NavigableSet
iteratorin interface
Set
iteratorin class
AbstractCollection
public Iterator
descendingIterator()
descendingIteratorin interface
NavigableSet
public NavigableSet
descendingSet()
removeoperation), the results of the iteration are undefined.
The returned set has an ordering equivalent to
Collections.reverseOrder
(comparator()).
The expression
s.descendingSet().descendingSet()
returns a
view of essentially equivalent to .
descendingSetin interface
NavigableSet
public int size()
sizein interface
Collection
sizein interface
Set
sizein class
AbstractCollection
public boolean isEmpty()
trueif this set contains no elements.
isEmptyin interface
Collection
isEmptyin interface
Set
isEmptyin class
AbstractCollection
trueif this set contains no elements
public boolean contains(Object o)
trueif this set contains the specified element. More formally, returns
trueif and only if this set contains an element
esuch that (o==null ? e==null : o.equals(e)).
containsin interface
Collection
containsin interface
Set
containsin class
AbstractCollection
o- object to be checked for containment in this set
trueif this set contains the specified element
ClassCastException- if the specified object cannot be compared with the elements currently in the set
NullPointerException- if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
public boolean add(E e)
eto this set if the set contains no element
e2such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns
false.
addin interface
Collection
addin interface
Set
addin class
AbstractCollection
e- element to be added to this set
trueif this set did not already contain the specified element
ClassCastException- if the specified object cannot be compared with the elements currently in this set
NullPointerException- if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
public boolean remove(Object o)
esuch that (o==null ? e==null : o.equals(e)), if this set contains such an element. Returns
trueif this set contained the element (or equivalently, if this set changed as a result of the call). (This set will not contain the element once the call returns.)
removein interface
Collection
removein interface
Set
removein class
AbstractCollection
o- object to be removed from this set, if present
trueif this set contained the specified element
ClassCastException- if the specified object cannot be compared with the elements currently in this set
NullPointerException- if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
public void clear()
clearin interface
Collection
clearin interface
Set
clearin class
AbstractCollection
public boolean addAll(Collection
extends E>
c)
addAllin interface
Collection
addAllin interface
Set
addAllin class
AbstractCollection
c- collection containing elements to be added to this set
trueif this set changed as a result of the call
ClassCastException- if the elements provided cannot be compared with the elements currently in the set
NullPointerException- if the specified collection is null or if any element is null and this set uses natural ordering, or its comparator does not permit null elements
AbstractCollection.add(Object)
public NavigableSet
subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)
fromElementto
toElement. If
fromElementand
toElementare equal, the returned set is empty unless
fromInclusiveand
toInclusiveare both true. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The returned set supports all optional set operations that this set supports.
The returned set will throw an
IllegalArgumentException
on an attempt to insert an element outside its range.
subSetin interface
NavigableSet
fromElement- low endpoint of the returned set
fromInclusive-
trueif the low endpoint is to be included in the returned view
toElement- high endpoint of the returned set
toInclusive-
trueif the high endpoint is to be included in the returned view
fromElement, inclusive, to
toElement, exclusive
ClassCastException- if
fromElementand
toElementcannot 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
fromElementor
toElementcannot be compared to elements currently in the set.
NullPointerException- if
fromElementor
toElementis null and this set uses natural ordering, or its comparator does not permit null elements
IllegalArgumentException- if
fromElementis greater than
toElement; or if this set itself has a restricted range, and
fromElementor
toElementlies outside the bounds of the range.
public NavigableSet
headSet(E toElement, boolean inclusive)
inclusiveis true)
toElement. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The returned set supports all optional set operations that this set supports.
The returned set will throw an
IllegalArgumentException
on an attempt to insert an element outside its range.
headSetin interface
NavigableSet
toElement- high endpoint of the returned set
inclusive-
trueif the high endpoint is to be included in the returned view
inclusiveis true)
toElement
ClassCastException- if
toElementis not compatible with this set's comparator (or, if the set has no comparator, if
toElementdoes not implement
Comparable). Implementations may, but are not required to, throw this exception if
toElementcannot be compared to elements currently in the set.
NullPointerException- if
toElementis null and this set uses natural ordering, or its comparator does not permit null elements
IllegalArgumentException- if this set itself has a restricted range, and
toElementlies outside the bounds of the range
public NavigableSet
tailSet(E fromElement, boolean inclusive)
inclusiveis true)
fromElement. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The returned set supports all optional set operations that this set supports.
The returned set will throw an
IllegalArgumentException
on an attempt to insert an element outside its range.
tailSetin interface
NavigableSet
fromElement- low endpoint of the returned set
inclusive-
trueif the low endpoint is to be included in the returned view
fromElement
ClassCastException- if
fromElementis not compatible with this set's comparator (or, if the set has no comparator, if
fromElementdoes not implement
Comparable). Implementations may, but are not required to, throw this exception if
fromElementcannot be compared to elements currently in the set.
NullPointerException- if
fromElementis null and this set uses natural ordering, or its comparator does not permit null elements
IllegalArgumentException- if this set itself has a restricted range, and
fromElementlies outside the bounds of the range
public SortedSet
subSet(E fromElement, E toElement)
The returned set will throw an IllegalArgumentException on an attempt to insert an element outside its range.
Equivalent to
subSet(fromElement, true, toElement, false)
.
subSetin interface
NavigableSet
subSetin interface
SortedSet
fromElement- low endpoint (inclusive) of the returned set
toElement- high endpoint (exclusive) of the returned set
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
fromElementor
toElementis 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
public SortedSet
headSet(E toElement)
The returned set will throw an IllegalArgumentException on an attempt to insert an element outside its range.
Equivalent to
headSet(toElement, false)
.
headSetin interface
NavigableSet
headSetin interface
SortedSet
toElement- high endpoint (exclusive) of the returned set
ClassCastException- if toElement is not compatible with this set's comparator (or, if the set has no comparator, if toElement does not implement
Comparable). Implementations may, but are not required to, throw this exception if toElement cannot be compared to elements currently in the set.
NullPointerException- if
toElementis null and this set uses natural ordering, or its comparator does not permit null elements
IllegalArgumentException- if this set itself has a restricted range, and toElement lies outside the bounds of the range
public SortedSet
tailSet(E fromElement)
The returned set will throw an IllegalArgumentException on an attempt to insert an element outside its range.
Equivalent to
tailSet(fromElement, true)
.
tailSetin interface
NavigableSet
tailSetin interface
SortedSet
fromElement- low endpoint (inclusive) of the returned set
ClassCastException- if fromElement is not compatible with this set's comparator (or, if the set has no comparator, if fromElement does not implement
Comparable). Implementations may, but are not required to, throw this exception if fromElement cannot be compared to elements currently in the set.
NullPointerException- if
fromElementis null and this set uses natural ordering, or its comparator does not permit null elements
IllegalArgumentException- if this set itself has a restricted range, and fromElement lies outside the bounds of the range
public Comparator
super E>
comparator()
comparatorin interface
SortedSet
public E first()
firstin interface
SortedSet
NoSuchElementException- if this set is empty
public E last()
lastin interface
SortedSet
NoSuchElementException- if this set is empty
public E lower(E e)
nullif there is no such element.
lowerin interface
NavigableSet
e- the value to match
e, or
nullif there is no such element
ClassCastException- if the specified element cannot be compared with the elements currently in the set
NullPointerException- if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
public E floor(E e)
nullif there is no such element.
floorin interface
NavigableSet
e- the value to match
e, or
nullif there is no such element
ClassCastException- if the specified element cannot be compared with the elements currently in the set
NullPointerException- if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
public E ceiling(E e)
nullif there is no such element.
ceilingin interface
NavigableSet
e- the value to match
e, or
nullif there is no such element
ClassCastException- if the specified element cannot be compared with the elements currently in the set
NullPointerException- if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
public E higher(E e)
nullif there is no such element.
higherin interface
NavigableSet
e- the value to match
e, or
nullif there is no such element
ClassCastException- if the specified element cannot be compared with the elements currently in the set
NullPointerException- if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
public E pollFirst()
nullif this set is empty.
pollFirstin interface
NavigableSet
nullif this set is empty
public E pollLast()
nullif this set is empty.
pollLastin interface
NavigableSet
nullif this set is empty
public Object clone()
TreeSetinstance. (The elements themselves are not cloned.)
public Spliterator
spliterator()
Spliteratorover the elements in this set.
The
Spliterator
reports
Spliterator.SIZED
,
Spliterator.DISTINCT
,
Spliterator.SORTED
, and
Spliterator.ORDERED
. Overriding implementations should document
the reporting of additional characteristic values.
The spliterator’s comparator (see
Spliterator.getComparator()
) is
null
if
the tree set’s comparator (see
comparator()
) is
null
.
Otherwise, the spliterator’s comparator is the same as or imposes the
same total ordering as the tree set’s comparator.
spliteratorin interface
Iterable
spliteratorin interface
Collection
spliteratorin interface
Set
spliteratorin interface
SortedSet
Spliteratorover the elements in this set
Submit a bug or feature For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.Copyright © 1993, 2024, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface.
It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used. The TreeSet implements a NavigableSet interface by inheriting AbstractSet class.
It can clearly be perceived from the above image that the navigable set extends the sorted set interface. Since a set doesn’t retain the insertion order, the navigable set interface provides the implementation to navigate through the Set. The class which implements the navigable set is a TreeSet which is an implementation of a self-balancing tree. Therefore, this interface provides us with a way to navigate through this tree.
Note:
- An object is said to be comparable if and only if the corresponding class implements a Comparable interface.
- String, StringBuffer class and all the Wrapper classes already implements Comparable interface Hence, we DO NOT get a ClassCastException. But if we are creating TreeSet of user defined classes or any Java classes which does not implements comparable interface we will get ClassCastException. to solve this problem we can either implement Comparable to our user defined class or we can pass Comparator object in Constructor while creating the set.
- For an empty tree-set, when trying to insert null as the first value, one will get NPE from JDK 7. From JDK 7 onwards, null is not at all accepted by TreeSet. However, up to JDK 6, null was accepted as the first value, but any insertion of more null values in the TreeSet resulted in NullPointerException. Hence, it was considered a bug and thus removed in JDK 7.
- TreeSet serves as an excellent choice for storing large amounts of sorted information which are supposed to be accessed quickly because of its faster access and retrieval time.
- The insertion of null values into a TreeSet throws NullPointerException because while insertion of null, it gets compared to the existing elements, and null cannot be compared to any value.
How does TreeSet work Internally?
TreeSet is basically an implementation of a self-balancing binary search tree like a Red-Black Tree. Therefore operations like add, remove, and search takes O(log(N)) time. The reason is that in a self-balancing tree, it is made sure that the height of the tree is always O(log(N)) for all the operations. Therefore, this is considered as one of the most efficient data structures in order to store the huge sorted data and perform operations on it. However, operations like printing N elements in the sorted order take O(N) time.
Now let us discuss Synchronized TreeSet prior moving ahead. The implementation of a TreeSet is not synchronized. This means that if multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing some object that naturally encapsulates the set. If no such object exists, the set should be “wrapped” using the Collections.synchronizedSortedSet method. This is best done at the creation time, to prevent accidental unsynchronized access to the set. It can be achieved as shown below as follows:
TreeSet ts = new TreeSet();
Set syncSet = Collections.synchronziedSet(ts);
Constructors of TreeSet Class are as follows:
In order to create a TreeSet, we need to create an object of the TreeSet class. The TreeSet class consists of various constructors which allow the possible creation of the TreeSet. The following are the constructors available in this class:
- TreeSet(): This constructor is used to build an empty TreeSet object in which elements will get stored in default natural sorting order.
Syntax: If we wish to create an empty TreeSet with the name ts, then, it can be created as:
TreeSet ts = new TreeSet();
- TreeSet(Comparator): This constructor is used to build an empty TreeSet object in which elements will need an external specification of the sorting order.
Syntax: If we wish to create an empty TreeSet with the name ts with an external sorting phenomenon, then, it can be created as:
TreeSet ts = new TreeSet(Comparator comp);
- TreeSet(Collection): This constructor is used to build a TreeSet object containing all the elements from the given collection in which elements will get stored in default natural sorting order. In short, this constructor is used when any conversion is needed from any Collection object to TreeSet object.
Syntax: If we wish to create a TreeSet with the name ts, then, it can be created as follows:
TreeSet t = new TreeSet(Collection col);
- TreeSet(SortedSet): This constructor is used to build a TreeSet object containing all the elements from the given sortedset in which elements will get stored in default natural sorting order. In short, this constructor is used to convert the SortedSet object to the TreeSet object.
Syntax: If we wish to create a TreeSet with the name ts, then, it can be created as follows:
TreeSet t = new TreeSet(SortedSet s);
Methods in TreeSet Class are depicted below in tabular format which later on we will be implementing to showcase in the implementation part.
TreeSet implements SortedSet so it has the availability of all methods in Collection, Set, and SortedSet interfaces. Following are the methods in the Treeset interface. In the table below, the “?” signifies that the method works with any type of object including user-defined objects.
Method | Description |
add(Object o) | This method will add the specified element according to the same sorting order mentioned during the creation of the TreeSet. Duplicate entries will not get added. |
addAll(Collection c) | This method will add all elements of the specified Collection to the set. Elements in the Collection should be homogeneous otherwise ClassCastException will be thrown. Duplicate Entries of Collection will not be added to TreeSet. |
ceiling?(E e) | This method returns the least element in this set greater than or equal to the given element, or null if there is no such element. |
clear() | This method will remove all the elements. |
clone() | The method is used to return a shallow copy of the set, which is just a simple copied set. |
Comparator comparator() | This method will return the Comparator used to sort elements in TreeSet or it will return null if the default natural sorting order is used. |
contains(Object o) | This method will return true if a given element is present in TreeSet else it will return false. |
descendingIterator?() | This method returns an iterator over the elements in this set in descending order. |
descendingSet?() | This method returns a reverse order view of the elements contained in this set. |
first() | This method will return the first element in TreeSet if TreeSet is not null else it will throw NoSuchElementException. |
floor?(E e) | This method returns the greatest element in this set less than or equal to the given element, or null if there is no such element. |
headSet(Object toElement) | This method will return elements of TreeSet which are less than the specified element. |
higher?(E e) | This method returns the least element in this set strictly greater than the given element, or null if there is no such element. |
isEmpty() | This method is used to return true if this set contains no elements or is empty and false for the opposite case. |
Iterator iterator() | Returns an iterator for iterating over the elements of the set. |
last() | This method will return the last element in TreeSet if TreeSet is not null else it will throw NoSuchElementException. |
lower?(E e) | This method returns the greatest element in this set strictly less than the given element, or null if there is no such element. |
pollFirst?() | This method retrieves and removes the first (lowest) element, or returns null if this set is empty. |
pollLast?() | This method retrieves and removes the last (highest) element, or returns null if this set is empty. |
remove(Object o) | This method is used to return a specific element from the set. |
size() | This method is used to return the size of the set or the number of elements present in the set. |
spliterator() | This method creates a late-binding and fail-fast Spliterator over the elements in this set. |
subSet(Object fromElement, Object toElement) | This method will return elements ranging from fromElement to toElement. fromElement is inclusive and toElement is exclusive. |
tailSet(Object fromElement) | This method will return elements of TreeSet which are greater than or equal to the specified element. |
Illustration: The following implementation demonstrates how to create and use a TreeSet.
Kết luận
Trong bài viết này, bạn đã tìm hiểu một TreeSet trong Java là gì, cách tạo một TreeSet, cách chuyển một bộ so sánh tùy chỉnh cho Treeset để thay đổi thứ tự sắp xếp của các phần tử, cách truy cập các phần tử của Treeset, cách loại bỏ các phần tử từ một TreeSet và cách tạo một TreeSet của các đối tượng do người dùng xác định.
All rights reserved
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order. The important points about the Java TreeSet class are: TreeSet is being implemented using a binary search tree, which is self-balancing just like a Red-Black Tree. Therefore, operations such as a search, remove, and add consume O(log(N)) time. The reason behind this is there in the self-balancing tree. It is there to ensure that the tree height never exceeds O(log(N)) for all of the mentioned operations. Therefore, it is one of the efficient data structures in order to keep the large data that is sorted and also to do operations on it. As already mentioned above, the TreeSet class is not synchronized. It means if more than one thread concurrently accesses a tree set, and one of the accessing threads modify it, then the synchronization must be done manually. It is usually done by doing some object synchronization that encapsulates the set. However, in the case where no such object is found, then the set must be wrapped with the help of the Collections.synchronizedSet() method. It is advised to use the method during creation time in order to avoid the unsynchronized access of the set. The following code snippet shows the same. As shown in the above diagram, the Java TreeSet class implements the NavigableSet interface. The NavigableSet interface extends SortedSet, Set, Collection and Iterable interfaces in hierarchical order. Let’s see the declaration for java.util.TreeSet class. Let’s see a simple example of Java TreeSet. FileName: TreeSet1.java Test it Now Output:
Let’s see an example of traversing elements in descending order. FileName: TreeSet2.java Test it Now Output:
Let’s see an example to retrieve and remove the highest and lowest Value. FileName: TreeSet3.java Output:
In this example, we perform various NavigableSet operations. FileName: TreeSet4.java Output:
In this example, we perform various SortedSetSet operations. FileName: TreeSet5.java Output:
Let’s see a TreeSet example where we are adding books to the set and printing all the books. The elements in TreeSet must be of a Comparable type. String and Wrapper classes are Comparable by default. To add user-defined objects in TreeSet, you need to implement the Comparable interface. FileName: TreeSetExample.java Output:
If we add an object of the class that is not implementing the Comparable interface, the ClassCast Exception is raised. Observe the following program. FileName: ClassCastExceptionTreeSet.java When we compile the above program, we get the ClassCastException, as shown below.
Explanation: In the above program, it is required to implement a Comparable interface. It is because the TreeSet maintains the sorting order, and for doing the sorting the comparison of different objects that are being inserted in the TreeSet is must, which is accomplished by implementing the Comparable interface. Next TopicJava PriorityQueue class |
Java Multithreading
- Java – Multithreading
- Java – Thread Life Cycle
- Java – Creating a Thread
- Java – Starting a Thread
- Java – Joining Threads
- Java – Naming Thread
- Java – Thread Scheduler
- Java – Thread Pools
- Java – Main Thread
- Java – Thread Priority
- Java – Daemon Threads
- Java – Thread Group
- Java – Shutdown Hook
Java Useful Resources
- Java Compiler
- Java – Questions and Answers
- Java – Quick Guide
- Java – Useful Resources
- Java – Discussion
- Java – Examples
Java – The TreeSet Class
TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in a sorted and 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.
Following is the list of the constructors supported by the TreeSet class.
Sr.No. | Constructor & Description |
TreeSet( ) This constructor constructs an empty tree set that will be sorted in an ascending order according to the natural order of its elements. |
|
TreeSet(Collection c) This constructor builds a tree set that contains the elements of the collection c. |
|
TreeSet(Comparator comp) This constructor constructs an empty tree set that will be sorted according to the given comparator. |
|
TreeSet(SortedSet ss) This constructor builds a TreeSet that contains the elements of the given SortedSet. |
Apart from the methods inherited from its parent classes, TreeSet defines the following methods −
Sr.No. | Method & Description |
void add(Object o) Adds the specified element to this set if it is not already present. |
|
boolean addAll(Collection c) Adds all of the elements in the specified collection to this set. |
|
void clear() Removes all of the elements from this set. |
|
Object clone() Returns a shallow copy of this TreeSet instance. |
|
Comparator comparator() Returns the comparator used to order this sorted set, or null if this tree set uses its elements natural ordering. |
|
boolean contains(Object o) Returns true if this set contains the specified element. |
|
Object first() Returns the first (lowest) element currently in this sorted set. |
|
SortedSet headSet(Object toElement) Returns a view of the portion of this set whose elements are strictly less than toElement. |
|
boolean isEmpty() Returns true if this set contains no elements. |
|
10 |
Iterator iterator() Returns an iterator over the elements in this set. |
11 |
Object last() Returns the last (highest) element currently in this sorted set. |
12 |
boolean remove(Object o) Removes the specified element from this set if it is present. |
13 |
int size() Returns the number of elements in this set (its cardinality). |
14 |
SortedSet subSet(Object fromElement, Object toElement) Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive. |
15 |
SortedSet tailSet(Object fromElement) Returns a view of the portion of this set whose elements are greater than or equal to fromElement. |
Java
|
A, B, For, Geek, Geeks, Z,
Features of a TreeSet:
- TreeSet implements the SortedSet interface. So, duplicate values are not allowed.
- Objects in a TreeSet are stored in a sorted and ascending order.
- TreeSet does not preserve the insertion order of elements but elements are sorted by keys.
- If we are depending on the default natural sorting order, the objects that are being inserted into the tree should be homogeneous and comparable. TreeSet does not allow the insertion of heterogeneous objects. It will throw a classCastException at Runtime if we try to add heterogeneous objects.
- The TreeSet can only accept generic types which are comparable.For example, the StringBuffer class implements the Comparable interface
Remove Elements
-
remove()
– removes the specified element from the set -
removeAll()
– removes all the elements from the set
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet
numbers = new TreeSet<>(); numbers.add(2); numbers.add(5); numbers.add(6); System.out.println("TreeSet: " + numbers); // Using the remove() method boolean value1 = numbers.remove(5); System.out.println("Is 5 removed? " + value1); // Using the removeAll() method boolean value2 = numbers.removeAll(numbers); System.out.println("Are all elements removed? " + value2); } }
Output
TreeSet: [2, 5, 6] Is 5 removed? true Are all elements removed? true
TreeSet với các đối tượng do người dùng xác định
Ví dụ trong phần này cho thấy cách tạo một TreeSet của các đối tượng do người dùng xác định.
Vì TreeSet cần giữ các đối tượng được sắp xếp, bạn phải triển khai Comparable interface trong lớp do người dùng xác định và cung cấp việc triển khai cho hàm compareTo() hoặc cung cấp Comparator tùy chỉnh tại thời điểm tạo ra TreeSet.
import java.util.Comparator; import java.util.Objects; import java.util.SortedSet; import java.util.TreeSet; class Employee implements Comparable
{ private int id; private String name; public Employee(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } // Two Employees are equal if their IDs are equal @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Employee employee = (Employee) o; return id == employee.id; } @Override public int hashCode() { return Objects.hash(id); } // Compare employees based on their IDs @Override public int compareTo(Employee employee) { return this.getId() - employee.getId(); } @Override public String toString() { return "Employee{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
public class TreeSetUserDefinedObjectExample { public static void main(String[] args) { // Creating a TreeSet of User Defined Objects. /* The requirement for a TreeSet of user defined objects is that 1. Either the class should implement the Comparable interface and provide the implementation for the compareTo() function. 2. Or you should provide a custom Comparator while creating the TreeSet. */ SortedSet
employees = new TreeSet<>(); // TreeSet uses the compareTo() method of the Employee class to compare two employees and sort them employees.add(new Employee(1010, "Rajeev")); employees.add(new Employee(1005, "Sachin")); employees.add(new Employee(1008, "Chris")); System.out.println("Employees (sorted based on Employee class's compareTo() function)"); System.out.println(employees); // Providing a Custom Comparator (This comparator compares the employees based on their Name) employees = new TreeSet<>(Comparator.comparing(Employee::getName)); employees.add(new Employee(1010, "Rajeev")); employees.add(new Employee(1005, "Sachin")); employees.add(new Employee(1008, "Chris")); System.out.println("\nEmployees (sorted based on the supplied Comparator)"); System.out.println(employees); } }
# Output Employees (sorted based on Employee class's compareTo() function) [Employee{id=1005, name='Sachin'}, Employee{id=1008, name='Chris'}, Employee{id=1010, name='Rajeev'}] Employees (sorted based on the supplied Comparator) [Employee{id=1008, name='Chris'}, Employee{id=1010, name='Rajeev'}, Employee{id=1005, name='Sachin'}]
Java Error & Exceptions
- Java – Exceptions
- Java – try-catch Block
- Java – try-with-resources
- Java – Multi-catch Block
- Java – Nested try Block
- Java – Finally Block
- Java – throw Exception
- Java – Exception Propagation
- Java – Built-in Exceptions
- Java – Custom Exception
Ví dụ về TreeSet trong java
Ví dụ 1: TreeSet trong java với String:
package vn.viettuts.collection; import java.util.TreeSet; public class TreeSetExample1 { public static void main(String[] args) { // init treeSet object TreeSet
treeSet = new TreeSet
(); treeSet.add(“Java”); treeSet.add(“C++”); treeSet.add(“Java”); treeSet.add(“PHP”); // show treeSet for (String str : treeSet) { System.out.println(str); } } }
Kết quả:
C++ Java PHP
Ví dụ 2: TreeSet trong java với đối tượng Student:
Chú ý: Phần tử của lớp TreeSet trong java phải được implements giao diện Comparable. Trong ví dụ này lớp Student phải được implements giao diện Comparable và phải override phương thức compareTo() để cài đặt các tiêu trí so sánh.
package vn.viettuts.collection; import java.util.TreeSet; /** * Student class * * @author viettuts.vn */ class Student implements Comparable
{ private String name; private int age; private String address; public Student() { } public Student(String name, int age, String address) { super(); this.name = name; this.age = age; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return “Student@name=” + name + “,age=” + age + “,address=” + address; } @Override public int compareTo(Student student) { // sort student’s name by ASC return this.getName().compareTo(student.getName()); } } /** * TreeSetExample2 class * * @author viettuts.vn */ public class TreeSetExample2 { public static void main(String[] args) { // init treeSet TreeSet
treeSet = new TreeSet
(); // create students object Student student1 = new Student(“Cong”, 17, “Hanoi”); Student student2 = new Student(“Dung”, 16, “Haiphong”); Student student3 = new Student(“Ngon”, 18, “Hanoi”); Student student4 = new Student(“Hanh”, 19, “Danang”); // add students object to treeSet treeSet.add(student1); treeSet.add(student2); treeSet.add(student3); treeSet.add(student4); treeSet.add(student1); // show treeSet for (Student student : treeSet) { System.out.println(student.toString()); } } }
Kết quả:
Student@name=Cong,age=17,address=Hanoi Student@name=Dung,age=16,address=Haiphong Student@name=Hanh,age=19,address=Danang Student@name=Ngon,age=18,address=Hanoi
Performance of TreeSet
When compared to a HashSet the performance of a TreeSet is on the lower side. Operations like add, remove and search take O(log n) time while operations like printing n elements in sorted order require O(n) time.
A TreeSet should be our primary choice if we want to keep our entries sorted as a TreeSet may be accessed and traversed in either ascending or descending order, and the performance of ascending operations and views is likely to be faster than that of descending ones.
The Principle of Locality – is a term for the phenomenon in which the same values, or related storage locations, are frequently accessed, depending on the memory access pattern.
When we say locality:
- Similar data is often accessed by an application with similar frequency
- If two entries are nearby given an ordering, a TreeSet places them near each other in the data structure, and hence in memory
A TreeSet being a data-structure with greater locality we can, therefore, conclude in accordance to the Principle of Locality, that we should give preference to a TreeSet if we’re short on memory and if we want to access elements that are relatively close to each other according to their natural ordering.
In case data needs to be read from the hard drive (which has greater latency than data read from the cache or memory) then prefer TreeSet as it has greater locality
Intro to TreeSet
Simply put, the TreeSet is a sorted collection that extends the AbstractSet class and implements the NavigableSet interface.
Here’s a quick summary of the most important aspects of this implementation:
- It stores unique elements
- It doesn’t preserve the insertion order of the elements
- It sorts the elements in ascending order
- It’s not thread-safe
In this implementation, objects are sorted and stored in ascending order according to their natural order. The TreeSet uses a self-balancing binary search tree, more specifically a Red-Black tree.
Simply put, being a self-balancing binary search tree, each node of the binary tree comprises of an extra bit, which is used to identify the color of the node which is either red or black. During subsequent insertions and deletions, these “color” bits helps in ensuring that the tree remains more or less balanced.
So, let’s create an instance of a TreeSet:
Set
treeSet = new TreeSet<>();
2.TreeSet With a Constructor Comparator Param
Optionally, we can construct a TreeSet with a constructor that lets us define the order in which the elements get sorted by using a Comparable or Comparator:
Set
treeSet = new TreeSet<>(Comparator.comparing(String::length));
Although TreeSet isn’t thread-safe, it can be synchronized externally using the Collections.synchronizedSet() wrapper:
Set
syncTreeSet = Collections.synchronizedSet(treeSet);
Alright, now that we have a clear idea of how to create a TreeSet instance, let’s have a look at the common operations we have available.
Java
|
Tree Set is [For, Geek, Geeks]
Contains Geeks true
First Value For
Last Value Geeks
Higher Geeks
Lower For
Operation 3: Removing the Values
The values can be removed from the TreeSet using the remove() method. There are various other methods that are used to remove the first value or the last value.
Example
Other Methods of TreeSet
Method | Description |
Creates a copy of the TreeSet | |
Searches the TreeSet for the specified element and returns a boolean result | |
Checks if the | |
Returns the size of the | |
Removes all the elements from the |
To learn more, visit Java TreeSet (official Java documentation).
Object Oriented Programming
- Java – OOPs Concepts
- Java – Object & Classes
- Java – Class Attributes
- Java – Class Methods
- Java – Methods
- Java – Variables Scope
- Java – Constructors
- Java – Access Modifiers
- Java – Inheritance
- Java – Aggregation
- Java – Polymorphism
- Java – Overriding
- Java – Method Overloading
- Java – Dynamic Binding
- Java – Static Binding
- Java – Instance Initializer Block
- Java – Abstraction
- Java – Encapsulation
- Java – Interfaces
- Java – Packages
- Java – Inner Classes
- Java – Static Class
- Java – Anonymous Class
- Java – Singleton Class
- Java – Wrapper Classes
- Java – Enums
Java Tutorial
- Java – Home
- Java – Overview
- Java – History
- Java – Features
- Java vs C++
- Java Virtual Machine(JVM)
- Java – JDK vs JRE vs JVM
- Java – Hello World Program
- Java – Environment Setup
- Java – Basic Syntax
- Java – Variable Types
- Java – Data Types
- Java – Type Casting
- Java – Unicode System
- Java – Basic Operators
- Java – Comments
Output
[A, B, C, D, E, F]
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface.
It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used. The TreeSet implements a NavigableSet interface by inheriting AbstractSet class.
It can clearly be perceived from the above image that the navigable set extends the sorted set interface. Since a set doesn’t retain the insertion order, the navigable set interface provides the implementation to navigate through the Set. The class which implements the navigable set is a TreeSet which is an implementation of a self-balancing tree. Therefore, this interface provides us with a way to navigate through this tree.
Note:
- An object is said to be comparable if and only if the corresponding class implements a Comparable interface.
- String, StringBuffer class and all the Wrapper classes already implements Comparable interface Hence, we DO NOT get a ClassCastException. But if we are creating TreeSet of user defined classes or any Java classes which does not implements comparable interface we will get ClassCastException. to solve this problem we can either implement Comparable to our user defined class or we can pass Comparator object in Constructor while creating the set.
- For an empty tree-set, when trying to insert null as the first value, one will get NPE from JDK 7. From JDK 7 onwards, null is not at all accepted by TreeSet. However, up to JDK 6, null was accepted as the first value, but any insertion of more null values in the TreeSet resulted in NullPointerException. Hence, it was considered a bug and thus removed in JDK 7.
- TreeSet serves as an excellent choice for storing large amounts of sorted information which are supposed to be accessed quickly because of its faster access and retrieval time.
- The insertion of null values into a TreeSet throws NullPointerException because while insertion of null, it gets compared to the existing elements, and null cannot be compared to any value.
How does TreeSet work Internally?
TreeSet is basically an implementation of a self-balancing binary search tree like a Red-Black Tree. Therefore operations like add, remove, and search takes O(log(N)) time. The reason is that in a self-balancing tree, it is made sure that the height of the tree is always O(log(N)) for all the operations. Therefore, this is considered as one of the most efficient data structures in order to store the huge sorted data and perform operations on it. However, operations like printing N elements in the sorted order take O(N) time.
Now let us discuss Synchronized TreeSet prior moving ahead. The implementation of a TreeSet is not synchronized. This means that if multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by synchronizing some object that naturally encapsulates the set. If no such object exists, the set should be “wrapped” using the Collections.synchronizedSortedSet method. This is best done at the creation time, to prevent accidental unsynchronized access to the set. It can be achieved as shown below as follows:
TreeSet ts = new TreeSet();
Set syncSet = Collections.synchronziedSet(ts);
Constructors of TreeSet Class are as follows:
In order to create a TreeSet, we need to create an object of the TreeSet class. The TreeSet class consists of various constructors which allow the possible creation of the TreeSet. The following are the constructors available in this class:
- TreeSet(): This constructor is used to build an empty TreeSet object in which elements will get stored in default natural sorting order.
Syntax: If we wish to create an empty TreeSet with the name ts, then, it can be created as:
TreeSet ts = new TreeSet();
- TreeSet(Comparator): This constructor is used to build an empty TreeSet object in which elements will need an external specification of the sorting order.
Syntax: If we wish to create an empty TreeSet with the name ts with an external sorting phenomenon, then, it can be created as:
TreeSet ts = new TreeSet(Comparator comp);
- TreeSet(Collection): This constructor is used to build a TreeSet object containing all the elements from the given collection in which elements will get stored in default natural sorting order. In short, this constructor is used when any conversion is needed from any Collection object to TreeSet object.
Syntax: If we wish to create a TreeSet with the name ts, then, it can be created as follows:
TreeSet t = new TreeSet(Collection col);
- TreeSet(SortedSet): This constructor is used to build a TreeSet object containing all the elements from the given sortedset in which elements will get stored in default natural sorting order. In short, this constructor is used to convert the SortedSet object to the TreeSet object.
Syntax: If we wish to create a TreeSet with the name ts, then, it can be created as follows:
TreeSet t = new TreeSet(SortedSet s);
Methods in TreeSet Class are depicted below in tabular format which later on we will be implementing to showcase in the implementation part.
TreeSet implements SortedSet so it has the availability of all methods in Collection, Set, and SortedSet interfaces. Following are the methods in the Treeset interface. In the table below, the “?” signifies that the method works with any type of object including user-defined objects.
Method | Description |
add(Object o) | This method will add the specified element according to the same sorting order mentioned during the creation of the TreeSet. Duplicate entries will not get added. |
addAll(Collection c) | This method will add all elements of the specified Collection to the set. Elements in the Collection should be homogeneous otherwise ClassCastException will be thrown. Duplicate Entries of Collection will not be added to TreeSet. |
ceiling?(E e) | This method returns the least element in this set greater than or equal to the given element, or null if there is no such element. |
clear() | This method will remove all the elements. |
clone() | The method is used to return a shallow copy of the set, which is just a simple copied set. |
Comparator comparator() | This method will return the Comparator used to sort elements in TreeSet or it will return null if the default natural sorting order is used. |
contains(Object o) | This method will return true if a given element is present in TreeSet else it will return false. |
descendingIterator?() | This method returns an iterator over the elements in this set in descending order. |
descendingSet?() | This method returns a reverse order view of the elements contained in this set. |
first() | This method will return the first element in TreeSet if TreeSet is not null else it will throw NoSuchElementException. |
floor?(E e) | This method returns the greatest element in this set less than or equal to the given element, or null if there is no such element. |
headSet(Object toElement) | This method will return elements of TreeSet which are less than the specified element. |
higher?(E e) | This method returns the least element in this set strictly greater than the given element, or null if there is no such element. |
isEmpty() | This method is used to return true if this set contains no elements or is empty and false for the opposite case. |
Iterator iterator() | Returns an iterator for iterating over the elements of the set. |
last() | This method will return the last element in TreeSet if TreeSet is not null else it will throw NoSuchElementException. |
lower?(E e) | This method returns the greatest element in this set strictly less than the given element, or null if there is no such element. |
pollFirst?() | This method retrieves and removes the first (lowest) element, or returns null if this set is empty. |
pollLast?() | This method retrieves and removes the last (highest) element, or returns null if this set is empty. |
remove(Object o) | This method is used to return a specific element from the set. |
size() | This method is used to return the size of the set or the number of elements present in the set. |
spliterator() | This method creates a late-binding and fail-fast Spliterator over the elements in this set. |
subSet(Object fromElement, Object toElement) | This method will return elements ranging from fromElement to toElement. fromElement is inclusive and toElement is exclusive. |
tailSet(Object fromElement) | This method will return elements of TreeSet which are greater than or equal to the specified element. |
Illustration: The following implementation demonstrates how to create and use a TreeSet.
Advanced Java
- Java – Command-Line Arguments
- Java – Lambda Expressions
- Java – Sending Email
- Java – Applet Basics
- Java – Documentation
- Java – Autoboxing and Unboxing
- Java – File Mismatch Method
- Java – REPL (JShell)
- Java – Optional Class
- Java – Method References
- Java – Functional Interfaces
Simple TreeSet
Ví dụ sau đây cho thấy cách tạo một TreeSet và thêm các phần tử mới vào nó. TreeSet sẽ được sắp xếp dựa trên thứ tự tự nhiên của các phần tử.
import java.util.SortedSet; import java.util.TreeSet; public class CreateTreeSetExample { public static void main(String[] args) { // Creating a TreeSet SortedSet
fruits = new TreeSet<>(); // Adding new elements to a TreeSet fruits.add("Banana"); fruits.add("Apple"); fruits.add("Pineapple"); fruits.add("Orange"); System.out.println("Fruits Set : " + fruits); // Duplicate elements are ignored fruits.add("Apple"); System.out.println("After adding duplicate element \"Apple\" : " + fruits); // This will be allowed because it's in lowercase. fruits.add("banana"); System.out.println("After adding \"banana\" : " + fruits); } }
# Output Fruits Set : [Apple, Banana, Orange, Pineapple] After adding duplicate element "Apple" : [Apple, Banana, Orange, Pineapple] After adding "banana" : [Apple, Banana, Orange, Pineapple, banana]
Java Tutorial
- Java – Home
- Java – Overview
- Java – History
- Java – Features
- Java vs C++
- Java Virtual Machine(JVM)
- Java – JDK vs JRE vs JVM
- Java – Hello World Program
- Java – Environment Setup
- Java – Basic Syntax
- Java – Variable Types
- Java – Data Types
- Java – Type Casting
- Java – Unicode System
- Java – Basic Operators
- Java – Comments
TreeSet last()
Analogously to the above example, this method will return the last element if the set is not empty:
@Test
public void whenCheckingLastElement_shouldReturnLastElement() {
TreeSet
treeSet = new TreeSet<>();
treeSet.add("First");
treeSet.add("Last");
assertEquals("Last", treeSet.last());
}
Insert Elements to TreeSet
-
add()
– inserts the specified element to the set -
addAll()
– inserts all the elements of the specified collection to the set
For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet
evenNumbers = new TreeSet<>(); // Using the add() method evenNumbers.add(2); evenNumbers.add(4); evenNumbers.add(6); System.out.println("TreeSet: " + evenNumbers); TreeSet
numbers = new TreeSet<>(); numbers.add(1); // Using the addAll() method numbers.addAll(evenNumbers); System.out.println("New TreeSet: " + numbers); } }
Output
TreeSet: [2, 4, 6] New TreeSet: [1, 2, 4, 6]
TreeSetHashSet
Both the
TreeSet
as well as the
HashSet
implements the
Set
interface. However, there exist some differences between them.
-
Unlike
HashSet
, elements in
TreeSet
are stored in some order. It is because
TreeSet
implements the
SortedSet
interface as well. -
TreeSet
provides some methods for easy navigation. For example,
first()
,
last()
,
headSet(
),
tailSet()
, etc. It is because
TreeSet
also implements the
NavigableSet
interface. -
HashSet
is faster than the
TreeSet
for basic operations like add, remove, contains and size.
Java
|
Feeling lost in the vast world of Backend Development? It’s time for a change! Join our Java Backend Development – Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
10 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment…
Sử dụng TreeSet trong Java
Bài đăng này đã không được cập nhật trong 4 năm
Class TreeSet là một phần của java collection framework. Nó implement từ interface NavigableSet, lớp này được kế thừa từ SortedSet.
Lớp TreeSet trong nội bộ sử dụng TreeMap để lưu trữ các phần tử. Các phần tử trong một TreeSet được sắp xếp theo thứ tự tự nhiên của chúng.
Bạn cũng có thể cung cấp một phương thức so sánh tùy chỉnh Comparator cho TreeSet tại thời điểm khởi tạo để cho phép nó sắp xếp các phần tử dựa trên bộ so sánh được cung cấp.
SortedSet interface cung cấp các hàm để giữ cho các phần tử được sắp xếp. Và NavigableSet interface cung cấp các hàm để điều hướng thông qua SortedSet.
Ví dụ, tìm phần tử lớn hơn hoặc nhỏ hơn phần tử đã cho, tìm phần tử đầu tiên và phần tử cuối cùng trong SortedSet.
Vì lớp TreeSet kế thừa từ NavigableSet interface, nên nó có những phương thức của cả NavigableSet cũng như SortedSet.
Một số đặc điểm quan trọng của TreeSet trong Java :
- TreeSet không chứa các phần tử trùng lặp.
- Các phần tử trong một TreeSet được sắp xếp theo thứ tự tự nhiên của chúng, hoặc dựa trên một bộ so sánh Comparator tùy chỉnh được cung cấp tại thời điểm khởi tạo TreeSet.
- TreeSet không thể chứa các giá trị null.
- TreeSet sử dụng TreeMap để lưu trữ các phần tử.
- TreeSet class không phải là một thread-safe. Bạn phải đồng bộ hóa rõ ràng quyền truy cập đồng thời vào TreeSet trong môi trường đa luồng.
Tạo một TreeSet
Ví dụ minh họa
Ví dụ sử dụng TreeSet với kiểu dữ liệu cơ bản (Wrapper)
package com.gpcoder.collection.treeset; import java.util.Set; import java.util.TreeSet; public class TreeSetExample2 { public static final int NUM_OF_ELEMENT = 5; public static void main(String[] args) { // Create set Set
set = new TreeSet<>(); set.add(“Item01”); set.add(“Item02”); set.add(“Item03”); set.add(“Item04”); set.add(“Item05”); set.add(“Item02”); set.add(“Item03″); // Show set through for-each for (String item : set) { System.out.print(item + ” “); } } }
Kết quả thực thi chương trình trên:
Item01 Item02 Item03 Item04 Item05
Ví dụ sử dụng TreeSet với kiểu do người dùng tự định nghĩa (Object)
Student.java
package com.gpcoder.collection.treeset; public class Student { private int id; private String name; public Student(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return “Student [id=” + id + “, name=” + name + “]”; } public String getName() { return name; } }
TreeSetExample.java
package com.gpcoder.collection.treeset; import java.util.Set; import java.util.TreeSet; public class TreeSetExample { public static final int NUM_OF_ELEMENT = 5; public static void main(String[] args) { // Create list with no comparator Set
students = new TreeSet<>(); Student student1 = new Student(1, “myname1”); Student student2 = new Student(2, “myname2”); Student student3 = new Student(3, “myname3”); Student student4 = new Student(4, “myname4”); Student student5 = new Student(5, “myname5”); students.add(student1); students.add(student3); students.add(student2); students.add(student5); students.add(student4); students.add(student2); students.add(student3); // Show set student for (Student student : students) { System.out.println(student); } } }
Kết quả thực thi chương trình trên:
Exception in thread “main” java.lang.ClassCastException: com.gpcoder.collection.treeset.Student cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(TreeMap.java:1294) at java.util.TreeMap.put(TreeMap.java:538) at java.util.TreeSet.add(TreeSet.java:255) at com.gpcoder.collection.treeset.TreeSetExample.main(TreeSetExample.java:17)
Đối với kiểu Object nếu bạn không cung cấp bộ so sánh (Comaparator) cho TreeSet thì bạn sẽ gặp lỗi như trên. Có 2 cách để cung cấp bộ Comparator:
-
Implement Comparator
và override phương thức compare(T obj1, T obj2).
-
Implement Comparable
và override phương thức compareTo(T obj).
Implement Comparator và override phương thức compare(T obj1, T obj2)
Student.java
package com.gpcoder.collection.treeset; public class Student { private int id; private String name; public Student(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return “Student [id=” + id + “, name=” + name + “]”; } public String getName() { return name; } }
StudentComparator.java
package com.gpcoder.collection.treeset; import java.util.Comparator; public class StudentComparator implements Comparator
{ @Override public int compare(Student o1, Student o2) { // sort student’s name by ASC return o1.getName().compareTo(o2.getName()); } }
TreeSetExample.java
package com.gpcoder.collection.treeset; import java.util.Set; import java.util.TreeSet; public class TreeSetExample { public static final int NUM_OF_ELEMENT = 5; public static void main(String[] args) { // Create list with StudentComparator Set
students = new TreeSet<>(new StudentComparator()); Student student1 = new Student(1, “myname1”); Student student2 = new Student(2, “myname2”); Student student3 = new Student(3, “myname3”); Student student4 = new Student(4, “myname4”); Student student5 = new Student(5, “myname5”); students.add(student1); students.add(student3); students.add(student2); students.add(student5); students.add(student4); students.add(student2); students.add(student3); // Show set student for (Student student : students) { System.out.println(student); } } }
Kết quả thực thi chương trình trên:
Student [id=1, name=myname1] Student [id=2, name=myname2] Student [id=3, name=myname3] Student [id=4, name=myname4] Student [id=5, name=myname5]
Implement Comparable và override phương thức compareTo(T obj)
Student.java
package com.gpcoder.collection.treeset; public class Student implements Comparable
{ private int id; private String name; public Student(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return “Student [id=” + id + “, name=” + name + “]”; } @Override public int compareTo(Student student) { // sort student’s name by ASC return this.getName().compareTo(student.getName()); } public String getName() { return name; } }
TreeSetExample.java
package com.gpcoder.collection.treeset; public class TreeSetExample { public static final int NUM_OF_ELEMENT = 5; public static void main(String[] args) { // Create list Set
students = new TreeSet<>(); Student student1 = new Student(1, “myname1”); Student student2 = new Student(2, “myname2”); Student student3 = new Student(3, “myname3”); Student student4 = new Student(4, “myname4”); Student student5 = new Student(5, “myname5”); students.add(student1); students.add(student3); students.add(student2); students.add(student5); students.add(student4); students.add(student2); students.add(student3); // Show set student for (Student student : students) { System.out.println(student); } } }
Kết quả thực thi chương trình trên:
Student [id=1, name=myname1] Student [id=2, name=myname2] Student [id=3, name=myname3] Student [id=4, name=myname4] Student [id=5, name=myname5]
Java
|
Tree Set is [For, Geek, Geeks]
Contains Geeks true
First Value For
Last Value Geeks
Higher Geeks
Lower For
Operation 3: Removing the Values
The values can be removed from the TreeSet using the remove() method. There are various other methods that are used to remove the first value or the last value.
Example
Giới thiệu
Lớp TreeSet trong Java cài đặt (implement) Set Interface, nó sử dụng một cây (tree) cho lưu giữ các phần tử. TreeSet kế thừa lớp (extends) AbstractSet và cài đặt (implement) NavigableSet Interface. Các đối tượng của lớp TreeSet được lưu trữ theo thứ tự tăng dần.
Các điểm quan trọng về lớp TreeSet trong java là:
- Chỉ chứa các phần tử duy nhất giống như HashSet.
- Duy trì thứ tự tăng dần.
- TreeSet không cho phép chứa phần tử null.
- Bạn cần phải cung cấp bộ Comparator trong khi tạo một TreeSet. Nếu bạn không cung cấp bộ so sánh (Comparator) cho TreeSet, các phần tử sẽ được đặt theo thứ tự tăng dần.
- TreeSet không được đồng bộ. Để có được một TreeSet đồng bộ, hãy sử dụng phương thức Collections.synchronizedSortedSet ().
- Độ phức tạp của TreeSet là log(n) cho thao tác thêm (insertion), loại bỏ (removal) và truy xuất (retrieval).
- TreeSet sử dụng TreeMap để lưu trữ các phần tử, giống như HashSet và LinkedHashSet sử dụng HashMap và LinkedHashMap tương ứng để lưu trữ các phần tử của chúng.
Java
|
Implementation:
Here we will be performing various operations over the TreeSet object to get familiar with the methods and concepts of TreeSet in java. Let’s see how to perform a few frequently used operations on the TreeSet. They are listed as follows:
- Adding elements
- Accessing elements
- Removing elements
- Iterating through elements
Now let us discuss each operation individually one by one later alongside grasping with the help of a clean java program.
Operation 1: Adding Elements
In order to add an element to the TreeSet, we can use the add() method. However, the insertion order is not retained in the TreeSet. Internally, for every element, the values are compared and sorted in ascending order. We need to keep a note that duplicate elements are not allowed and all the duplicate elements are ignored. And also, Null values are not accepted by the TreeSet.
Example
Object Oriented Programming
- Java – OOPs Concepts
- Java – Object & Classes
- Java – Class Attributes
- Java – Class Methods
- Java – Methods
- Java – Variables Scope
- Java – Constructors
- Java – Access Modifiers
- Java – Inheritance
- Java – Aggregation
- Java – Polymorphism
- Java – Overriding
- Java – Method Overloading
- Java – Dynamic Binding
- Java – Static Binding
- Java – Instance Initializer Block
- Java – Abstraction
- Java – Encapsulation
- Java – Interfaces
- Java – Packages
- Java – Inner Classes
- Java – Static Class
- Java – Anonymous Class
- Java – Singleton Class
- Java – Wrapper Classes
- Java – Enums
TreeSet size()
The size() method is used to identify the number of elements present in the TreeSet. It’s one of the fundamental methods in the API:
@Test
public void whenCheckingTheSizeOfTreeSet_shouldReturnThesize() {
Set
treeSetSize = new TreeSet<>();
treeSetSize.add("String Added");
assertEquals(1, treeSetSize.size());
}
Advanced Java
- Java – Command-Line Arguments
- Java – Lambda Expressions
- Java – Sending Email
- Java – Applet Basics
- Java – Documentation
- Java – Autoboxing and Unboxing
- Java – File Mismatch Method
- Java – REPL (JShell)
- Java – Optional Class
- Java – Method References
- Java – Functional Interfaces
Java Useful Resources
- Java Compiler
- Java – Questions and Answers
- Java – Quick Guide
- Java – Useful Resources
- Java – Discussion
- Java – Examples
Java – The TreeSet Class
TreeSet provides an implementation of the Set interface that uses a tree for storage. Objects are stored in a sorted and 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.
Following is the list of the constructors supported by the TreeSet class.
Sr.No. | Constructor & Description |
TreeSet( ) This constructor constructs an empty tree set that will be sorted in an ascending order according to the natural order of its elements. |
|
TreeSet(Collection c) This constructor builds a tree set that contains the elements of the collection c. |
|
TreeSet(Comparator comp) This constructor constructs an empty tree set that will be sorted according to the given comparator. |
|
TreeSet(SortedSet ss) This constructor builds a TreeSet that contains the elements of the given SortedSet. |
Apart from the methods inherited from its parent classes, TreeSet defines the following methods −
Sr.No. | Method & Description |
void add(Object o) Adds the specified element to this set if it is not already present. |
|
boolean addAll(Collection c) Adds all of the elements in the specified collection to this set. |
|
void clear() Removes all of the elements from this set. |
|
Object clone() Returns a shallow copy of this TreeSet instance. |
|
Comparator comparator() Returns the comparator used to order this sorted set, or null if this tree set uses its elements natural ordering. |
|
boolean contains(Object o) Returns true if this set contains the specified element. |
|
Object first() Returns the first (lowest) element currently in this sorted set. |
|
SortedSet headSet(Object toElement) Returns a view of the portion of this set whose elements are strictly less than toElement. |
|
boolean isEmpty() Returns true if this set contains no elements. |
|
10 |
Iterator iterator() Returns an iterator over the elements in this set. |
11 |
Object last() Returns the last (highest) element currently in this sorted set. |
12 |
boolean remove(Object o) Removes the specified element from this set if it is present. |
13 |
int size() Returns the number of elements in this set (its cardinality). |
14 |
SortedSet subSet(Object fromElement, Object toElement) Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive. |
15 |
SortedSet tailSet(Object fromElement) Returns a view of the portion of this set whose elements are greater than or equal to fromElement. |
So sánh Comparable vs Comparator
Comparable | Comparator |
Comparable chỉ cung cấp một cách so sánh duy nhất. Tức là chúng ta chỉ có thể so sánh theo id hoặc name, hoặc age, … | Comparable cung cấp nhiều cách so sánh. Tức là chúng ta có thể sắp xếp dựa trên nhiều yếu tố như id, name, age, … |
Comparable làm thay đổi lớp gốc (original class), tức là lớp của đối tượng so sánh phải chỉnh sửa và implement Comparable Interface để cài đặt bộ so sánh. | Comparator không làm thay đổi lớp gốc (original class). Chúng ta có thể tạo một class mới, implement Comparator Interface để cài đặt bộ so sánh. |
Comparable cung cấp phương thức compareTo() để so sánh 2 phần tử. | Comparable cung cấp phương thức compare() để so sánh 2 phần tử. |
Comparable nằm trong package java.lang. | Comparator nằm trong package java.util. |
Có thể sắp xếp một danh sách bất kỳ bằng phương thức Collections.sort(List). | Có thể sắp xếp một danh sách bất kỳ bằng phương thức Collections.sort(List, Comparator). |
Ví dụ tạo chỉ có thể tạo một Comparable
Một class Student chỉ có thể cài đặt một phương thức compareTo của Comparator interface
public class Student2 implements Comparable
{ private int id; private String name; public Student2(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return “Student [id=” + id + “, name=” + name + “]”; } @Override public int compareTo(Student2 student) { // sort student’s name by ASC return this.getName().compareTo(student.getName()); } public String getName() { return name; } }
Ví dụ có thể tạo nhiều Comparator
Có thể tạo nhiều comparator cho class Student bằng cách tạo nhiều class Comparator và override phương thức compare của Comparator Interface.
Student.java
public class Student { private int id; private String name; public Student(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return “Student [id=” + id + “, name=” + name + “]”; } public int getId() { return id; } public String getName() { return name; } }
StudentComparator.java
import java.util.Comparator; public class StudentComparator implements Comparator
{ @Override public int compare(Student o1, Student o2) { // sort student’s name by ASC return o1.getName().compareTo(o2.getName()); } }
StudentIdComparator.java
import java.util.Comparator; public class StudentIdComparator implements Comparator
{ @Override public int compare(Student o1, Student o2) { // sort student’s id by DESC return o2.getName().compareTo(o1.getName()); } }
Ví dụ sử dụng Comparator để sắp xếp danh sách (List)
SortListExample.java
package com.gpcoder.collection.treeset; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SortListExample { public static final int NUM_OF_ELEMENT = 5; public static void main(String[] args) { // Create list List
students = new ArrayList<>(); Student student1 = new Student(1, “myname1”); Student student2 = new Student(2, “myname2”); Student student3 = new Student(3, “myname3”); Student student4 = new Student(4, “myname4”); Student student5 = new Student(5, “myname5”); students.add(student1); students.add(student3); students.add(student2); students.add(student5); students.add(student4); students.add(student2); // Show list student System.out.println(“List without sorted: “); printData(students); System.out.println(“— “); System.out.println(“List sorted using StudentNameComparator: “); List
students2 = new ArrayList<>(students); Collections.sort(students2, new StudentNameComparator()); printData(students2); System.out.println(“— “); System.out.println(“List sorted using StudentIdComparator: “); List
students3 = new ArrayList<>(students); Collections.sort(students3, new StudentIdComparator()); printData(students3); System.out.println(“— “); } public static void printData(List
students) { for (Student student : students) { System.out.println(student); } } }
Kết quả thực thi chương trình trên:
List without sorted: Student [id=1, name=myname1] Student [id=3, name=myname3] Student [id=2, name=myname2] Student [id=5, name=myname5] Student [id=4, name=myname4] Student [id=2, name=myname2] — List sorted using StudentNameComparator: Student [id=1, name=myname1] Student [id=2, name=myname2] Student [id=2, name=myname2] Student [id=3, name=myname3] Student [id=4, name=myname4] Student [id=5, name=myname5] — List sorted using StudentIdComparator: Student [id=5, name=myname5] Student [id=4, name=myname4] Student [id=3, name=myname3] Student [id=2, name=myname2] Student [id=2, name=myname2] Student [id=1, name=myname1] —
Sử dụng Anonymous Class: Comparable, Comparator
Student.java
package com.gpcoder.collection.treeset; public class Student { private int id; private String name; public Student(int id, String name) { this.id = id; this.name = name; } @Override public String toString() { return “Student [id=” + id + “, name=” + name + “]”; } public int getId() { return id; } public String getName() { return name; } }
SortListExample.java
package com.gpcoder.collection.treeset; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class SortListExample { public static final int NUM_OF_ELEMENT = 5; public static void main(String[] args) { // Create list List
students = new ArrayList<>(); Student student1 = new Student(1, “myname1”); Student student2 = new Student(2, “myname2”); Student student3 = new Student(3, “myname3”); Student student4 = new Student(4, “myname4”); Student student5 = new Student(5, “myname5”); students.add(student1); students.add(student3); students.add(student2); students.add(student5); students.add(student4); students.add(student2); // Show list student System.out.println(“List without sorted: “); printData(students); System.out.println(“— “); System.out.println(“List sorted using Comparable: “); List
students2 = new ArrayList<>(students); Collections.sort(students2, new Comparator
() { @Override public int compare(Student o1, Student o2) { // sort student’s name by ASC return o1.getName().compareTo(o2.getName()); } }); printData(students2); System.out.println(“— “); System.out.println(“List sorted using Comparable: “); List
students3 = new ArrayList<>(students); Collections.sort(students3, new Comparator
() { @Override public int compare(Student o1, Student o2) { // sort student’s id by DESC return o2.getName().compareTo(o1.getName()); } }); printData(students3); System.out.println(“— “); } public static void printData(List
students) { for (Student student : students) { System.out.println(student); } } }
Kết quả thực thi chương trình trên:
List without sorted: Student [id=1, name=myname1] Student [id=3, name=myname3] Student [id=2, name=myname2] Student [id=5, name=myname5] Student [id=4, name=myname4] Student [id=2, name=myname2] — List sorted using Comparable: Student [id=1, name=myname1] Student [id=2, name=myname2] Student [id=2, name=myname2] Student [id=3, name=myname3] Student [id=4, name=myname4] Student [id=5, name=myname5] — List sorted using Comparable: Student [id=5, name=myname5] Student [id=4, name=myname4] Student [id=3, name=myname3] Student [id=2, name=myname2] Student [id=2, name=myname2] Student [id=1, name=myname1] —
Java Multithreading
- Java – Multithreading
- Java – Thread Life Cycle
- Java – Creating a Thread
- Java – Starting a Thread
- Java – Joining Threads
- Java – Naming Thread
- Java – Thread Scheduler
- Java – Thread Pools
- Java – Main Thread
- Java – Thread Priority
- Java – Daemon Threads
- Java – Thread Group
- Java – Shutdown Hook
Storing Null Elements
Before Java 7, it was possible to add null elements to an empty TreeSet.
However, that was considered a bug. Therefore, TreeSet no longer supports the addition of null.
When we add elements to the TreeSet, the elements get sorted according to their natural order or as specified by the comparator. Hence adding a null, when compared to existing elements, results in a NullPointerException since null cannot be compared to any value:
@Test(expected = NullPointerException.class)
public void whenAddingNullToNonEmptyTreeSet_shouldThrowException() {
Set
treeSet = new TreeSet<>();
treeSet.add("First");
treeSet.add(null);
}
Elements inserted into the TreeSet must either implement the Comparable interface or at least be accepted by the specified comparator. All such elements must be mutually comparable, i.e. e1.compareTo(e2) or comparator.compare(e1, e2) mustn’t throw a ClassCastException.
Let’s see an example:
class Element {
private Integer id;
// Other methods...
}
Comparator
comparator = (ele1, ele2) -> {
return ele1.getId().compareTo(ele2.getId());
};
@Test
public void whenUsingComparator_shouldSortAndInsertElements() {
Set
treeSet = new TreeSet<>(comparator);
Element ele1 = new Element();
ele1.setId(100);
Element ele2 = new Element();
ele2.setId(200);
treeSet.add(ele1);
treeSet.add(ele2);
System.out.println(treeSet);
}
Java
|
[For, Geek, Geeks]
Operation 2: Accessing the Elements
After adding the elements, if we wish to access the elements, we can use inbuilt methods like contains(), first(), last(), etc.
Example
TreeSet remove()
The remove() method is used to remove the specified element from the set if it’s present.
If a set contained the specified element, this method returns true.
Let’s see it in action:
@Test
public void whenRemovingElement_shouldRemoveElement() {
Set
removeFromTreeSet = new TreeSet<>();
removeFromTreeSet.add("String Added");
assertTrue(removeFromTreeSet.remove("String Added"));
}
TreeSet Comparator
In all the examples above, tree set elements are sorted naturally. However, we can also customize the ordering of elements.
For this, we need to create our own comparator class based on which elements in a tree set are sorted. For example,
import java.util.TreeSet; import java.util.Comparator; class Main { public static void main(String[] args) { // Creating a tree set with a customized comparator TreeSet
animals = new TreeSet<>(new CustomComparator()); animals.add("Dog"); animals.add("Zebra"); animals.add("Cat"); animals.add("Horse"); System.out.println("TreeSet: " + animals); } // Creating a comparator class public static class CustomComparator implements Comparator
{ @Override public int compare(String animal1, String animal2) { int value = animal1.compareTo(animal2); // elements are sorted in reverse order if (value > 0) { return -1; } else if (value < 0) { return 1; } else { return 0; } } } }
Output
TreeSet: [Zebra, Horse, Dog, Cat]
In the above example, we have created a tree set passing CustomComparator class as an argument.
The CustomComparator class implements the
Comparator
interface.
We then override the
compare()
method. The method will now sort elements in reverse order.
To learn more, visit Java Comparator (official Java documentation).
Example
The following program illustrates several of the methods supported by this collection −
import java.util.*; public class TreeSetDemo { public static void main(String args[]) { // Create a tree set TreeSet ts = new TreeSet(); // Add elements to the tree set ts.add(“C”); ts.add(“A”); ts.add(“B”); ts.add(“E”); ts.add(“F”); ts.add(“D”); System.out.println(ts); } }
This will produce the following result −
Java
|
Output:
Now it’s time to implement TreeSet to understand better via implementing it.
Example 1:
TreeSet iterator()
The iterator() method returns an iterator iterating in the ascending order over the elements in the Set. Those iterators are fail-fast.
We can observe the ascending iteration order here:
@Test
public void whenIteratingTreeSet_shouldIterateTreeSetInAscendingOrder() {
Set
treeSet = new TreeSet<>();
treeSet.add("First");
treeSet.add("Second");
treeSet.add("Third");
Iterator
itr = treeSet.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
Additionally, TreeSet enables us to iterate through the Set in descending order.
Let’s see that in action:
@Test
public void whenIteratingTreeSet_shouldIterateTreeSetInDescendingOrder() {
TreeSet
treeSet = new TreeSet<>();
treeSet.add("First");
treeSet.add("Second");
treeSet.add("Third");
Iterator
itr = treeSet.descendingIterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
The Iterator throws a ConcurrentModificationException if the set is modified at any time after the iterator is created in any way except through the iterator’s remove() method.
Let’s create a test for this:
@Test(expected = ConcurrentModificationException.class)
public void whenModifyingTreeSetWhileIterating_shouldThrowException() {
Set
treeSet = new TreeSet<>();
treeSet.add("First");
treeSet.add("Second");
treeSet.add("Third");
Iterator
itr = treeSet.iterator();
while (itr.hasNext()) {
itr.next();
treeSet.remove("Second");
}
}
Alternatively, if we had used the iterator’s remove method, then we wouldn’t have encountered the exception:
@Test
public void whenRemovingElementUsingIterator_shouldRemoveElement() {
Set
treeSet = new TreeSet<>();
treeSet.add("First");
treeSet.add("Second");
treeSet.add("Third");
Iterator
itr = treeSet.iterator();
while (itr.hasNext()) {
String element = itr.next();
if (element.equals("Second"))
itr.remove();
}
assertEquals(2, treeSet.size());
}
There’s no guarantee on the fail-fast behavior of an iterator as it’s impossible to make any hard guarantees in the presence of unsynchronized concurrent modification.
More about this can be found here.
TreeSet first()
This method returns the first element from a TreeSet if it’s not empty. Otherwise, it throws a NoSuchElementException.
Let’s see an example:
@Test
public void whenCheckingFirstElement_shouldReturnFirstElement() {
TreeSet
treeSet = new TreeSet<>();
treeSet.add("First");
assertEquals("First", treeSet.first());
}
Conclusion
In this article, we focus on understanding how to use the standard TreeSet implementation in Java. We saw its purpose and how efficient it is regarding usability given its ability to avoid duplicates and sort elements.
As always, code snippets can be found over on GitHub.
The
TreeSet
class of the Java collections framework provides the functionality of a tree data structure.
It extends the NavigableSet interface.
TreeSet tailSet()
This method will return the elements of a TreeSet which are greater than or equal to the specified element:
@Test
public void whenUsingTailSet_shouldReturnTailSetElements() {
NavigableSet
treeSet = new TreeSet<>();
treeSet.add(1);
treeSet.add(2);
treeSet.add(3);
treeSet.add(4);
treeSet.add(5);
treeSet.add(6);
Set
subSet = treeSet.tailSet(3);
assertEquals(subSet, treeSet.subSet(3, true, 6, true));
}
Creating a TreeSet
In order to create a tree set, we must import the
java.util.TreeSet
package first.
Once we import the package, here is how we can create a
TreeSet
in Java.
TreeSet
numbers = new TreeSet<>();
Here, we have created a
TreeSet
without any arguments. In this case, the elements in
TreeSet
are sorted naturally (ascending order).
However, we can customize the sorting of elements by using the
Comparator
interface. We will learn about it later in this tutorial.
TreeSet subSet()
This method will return the elements ranging from fromElement to toElement. Note that fromElement is inclusive and toElement is exclusive:
@Test
public void whenUsingSubSet_shouldReturnSubSetElements() {
SortedSet
treeSet = new TreeSet<>();
treeSet.add(1);
treeSet.add(2);
treeSet.add(3);
treeSet.add(4);
treeSet.add(5);
treeSet.add(6);
Set
expectedSet = new TreeSet<>();
expectedSet.add(2);
expectedSet.add(3);
expectedSet.add(4);
expectedSet.add(5);
Set
subSet = treeSet.subSet(2, 6);
assertEquals(expectedSet, subSet);
}
Hierarchy của lớp TreeSet
Lớp java.util.TreeSet được định nghĩa như sau:
public class TreeSet
extends AbstractSet
implements NavigableSet
, Cloneable, java.io.Serializable { private transient NavigableMap
m; private static final Object PRESENT = new Object(); TreeSet(NavigableMap
m) { this.m = m; } public TreeSet() { this(new TreeMap
()); } }
TreeSet headSet()
This method will return elements of TreeSet which are smaller than the specified element:
@Test
public void whenUsingHeadSet_shouldReturnHeadSetElements() {
SortedSet
treeSet = new TreeSet<>();
treeSet.add(1);
treeSet.add(2);
treeSet.add(3);
treeSet.add(4);
treeSet.add(5);
treeSet.add(6);
Set
subSet = treeSet.headSet(6);
assertEquals(subSet, treeSet.subSet(1, 6));
}
Java
|
Implementation:
Here we will be performing various operations over the TreeSet object to get familiar with the methods and concepts of TreeSet in java. Let’s see how to perform a few frequently used operations on the TreeSet. They are listed as follows:
- Adding elements
- Accessing elements
- Removing elements
- Iterating through elements
Now let us discuss each operation individually one by one later alongside grasping with the help of a clean java program.
Operation 1: Adding Elements
In order to add an element to the TreeSet, we can use the add() method. However, the insertion order is not retained in the TreeSet. Internally, for every element, the values are compared and sorted in ascending order. We need to keep a note that duplicate elements are not allowed and all the duplicate elements are ignored. And also, Null values are not accepted by the TreeSet.
Example
Set Operations
The methods of the
TreeSet
class can also be used to perform various set operations.
Union of Sets
To perform the union between two sets, we use the
addAll()
method. For example,
import java.util.TreeSet;; class Main { public static void main(String[] args) { TreeSet
evenNumbers = new TreeSet<>(); evenNumbers.add(2); evenNumbers.add(4); System.out.println("TreeSet1: " + evenNumbers); TreeSet
numbers = new TreeSet<>(); numbers.add(1); numbers.add(2); numbers.add(3); System.out.println("TreeSet2: " + numbers); // Union of two sets numbers.addAll(evenNumbers); System.out.println("Union is: " + numbers); } }
Output
TreeSet1: [2, 4] TreeSet2: [1, 2, 3] Union is: [1, 2, 3, 4]
Intersection of Sets
To perform the intersection between two sets, we use the
retainAll()
method. For example,
import java.util.TreeSet;; class Main { public static void main(String[] args) { TreeSet
evenNumbers = new TreeSet<>(); evenNumbers.add(2); evenNumbers.add(4); System.out.println("TreeSet1: " + evenNumbers); TreeSet
numbers = new TreeSet<>(); numbers.add(1); numbers.add(2); numbers.add(3); System.out.println("TreeSet2: " + numbers); // Intersection of two sets numbers.retainAll(evenNumbers); System.out.println("Intersection is: " + numbers); } }
Output
TreeSet1: [2, 4] TreeSet2: [1, 2, 3] Intersection is: [2]
Difference of Sets
To calculate the difference between the two sets, we can use the
removeAll()
method. For example,
import java.util.TreeSet;; class Main { public static void main(String[] args) { TreeSet
evenNumbers = new TreeSet<>(); evenNumbers.add(2); evenNumbers.add(4); System.out.println("TreeSet1: " + evenNumbers); TreeSet
numbers = new TreeSet<>(); numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); System.out.println("TreeSet2: " + numbers); // Difference between two sets numbers.removeAll(evenNumbers); System.out.println("Difference is: " + numbers); } }
Output
TreeSet1: [2, 4] TreeSet2: [1, 2, 3, 4] Difference is: [1, 3]
Subset of a Set
To check if a set is a subset of another set or not, we use the
containsAll()
method. For example,
import java.util.TreeSet; class Main { public static void main(String[] args) { TreeSet
numbers = new TreeSet<>(); numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); System.out.println("TreeSet1: " + numbers); TreeSet
primeNumbers = new TreeSet<>(); primeNumbers.add(2); primeNumbers.add(3); System.out.println("TreeSet2: " + primeNumbers); // Check if primeNumbers is subset of numbers boolean result = numbers.containsAll(primeNumbers); System.out.println("Is TreeSet2 subset of TreeSet1? " + result); } }
Output
TreeSet1: [1, 2, 3, 4] TreeSet2: [2, 3] Is TreeSet2 subset of TreeSet1? True
Java
|
Feeling lost in the vast world of Backend Development? It’s time for a change! Join our Java Backend Development – Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
10 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment…
When it comes to discussing differences between Set the firstmost thing that comes into play is the insertion order and how elements will be processed. HashSet in java is a class implementing the Set interface, backed by a hash table which is actually a HashMap instance. This class permits the null element. The class also offers constant time performance for the basic operations like add, remove, contains, and size assuming the hash function disperses the elements properly among the buckets while TreeSet is an implementation of the SortedSet interface which as the name suggests uses the tree for storage purposes where here the ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided.
Speed and internal implementation
For operations like search, insert, and delete HashSet takes constant time for these operations on average. HashSet is faster than TreeSet. HashSet is Implemented using a hash table. TreeSet takes O(Log n) for search, insert and delete which is higher than HashSet. But TreeSet keeps sorted data. Also, it supports operations like higher() (Returns least higher element), floor(), ceiling(), etc. These operations are also O(Log n) in TreeSet and not supported in HashSet. TreeSet is implemented using a self-balancing binary search tree (Red-Black Tree). TreeSet is backed by TreeMap in Java.
Ordering
Elements in HashSet are not ordered. TreeSet maintains objects in Sorted order defined by either Comparable or Comparator method in Java. TreeSet elements are sorted in ascending order by default. It offers several methods to deal with the ordered set like first(), last(), headSet(), tailSet(), etc.
Null Object
HashSet allows null object. TreeSet doesn’t allow null Object and throw NullPointerException, Why, because TreeSet uses compareTo() method to compare keys and compareTo() will throw java.lang.NullPointerException.
Comparison
HashSet uses the equals() method to compare two objects in Set and for detecting duplicates. TreeSet uses compareTo() method for same purpose. If equals() and compareTo() are not consistent, i.e. for two equal objects equals should return true while compareTo() should return zero, then it will break the contract of Set interface and will allow duplicates in Set implementations like TreeSet
Note: If you want a sorted Set then it is better to add elements to HashSet and then convert it into TreeSet rather than creating a TreeSet and adding elements to it.
Geek after going through their differences now you must be wondering when to prefer TreeSet over HashSet?
- Sorted unique elements are required instead of unique elements. The sorted list given by TreeSet is always in ascending order.
- TreeSet has a greater locality than HashSet.If two entries are nearby in the order, then TreeSet places them near each other in data structure and hence in memory, while HashSet spreads the entries all over memory regardless of the keys they are associated to.
- TreeSet uses a Red-Black tree algorithm underneath to sort out the elements. When one needs to perform read/write operations frequently, then TreeSet is a good choice.
- LinkedHashSet is another data structure that is between these two. It provides time complexities like HashSet and maintains the order of insertion (Note that this is not sorted order, but the order in which elements are inserted).
Implementation: Here we will be discussing them both with 2 examples for both of them. Let us start with HashSet later on dwelling on to TreeSet.
- HashSet examples
- TreeSet examples
Example 1:
Java
|
Output:
Feeling lost in the vast world of Backend Development? It’s time for a change! Join our Java Backend Development – Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
02 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment…
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending order. The important points about the Java TreeSet class are: TreeSet is being implemented using a binary search tree, which is self-balancing just like a Red-Black Tree. Therefore, operations such as a search, remove, and add consume O(log(N)) time. The reason behind this is there in the self-balancing tree. It is there to ensure that the tree height never exceeds O(log(N)) for all of the mentioned operations. Therefore, it is one of the efficient data structures in order to keep the large data that is sorted and also to do operations on it. As already mentioned above, the TreeSet class is not synchronized. It means if more than one thread concurrently accesses a tree set, and one of the accessing threads modify it, then the synchronization must be done manually. It is usually done by doing some object synchronization that encapsulates the set. However, in the case where no such object is found, then the set must be wrapped with the help of the Collections.synchronizedSet() method. It is advised to use the method during creation time in order to avoid the unsynchronized access of the set. The following code snippet shows the same. As shown in the above diagram, the Java TreeSet class implements the NavigableSet interface. The NavigableSet interface extends SortedSet, Set, Collection and Iterable interfaces in hierarchical order. Let’s see the declaration for java.util.TreeSet class. Let’s see a simple example of Java TreeSet. FileName: TreeSet1.java Test it Now Output:
Let’s see an example of traversing elements in descending order. FileName: TreeSet2.java Test it Now Output:
Let’s see an example to retrieve and remove the highest and lowest Value. FileName: TreeSet3.java Output:
In this example, we perform various NavigableSet operations. FileName: TreeSet4.java Output:
In this example, we perform various SortedSetSet operations. FileName: TreeSet5.java Output:
Let’s see a TreeSet example where we are adding books to the set and printing all the books. The elements in TreeSet must be of a Comparable type. String and Wrapper classes are Comparable by default. To add user-defined objects in TreeSet, you need to implement the Comparable interface. FileName: TreeSetExample.java Output:
If we add an object of the class that is not implementing the Comparable interface, the ClassCast Exception is raised. Observe the following program. FileName: ClassCastExceptionTreeSet.java When we compile the above program, we get the ClassCastException, as shown below.
Explanation: In the above program, it is required to implement a Comparable interface. It is because the TreeSet maintains the sorting order, and for doing the sorting the comparison of different objects that are being inserted in the TreeSet is must, which is accomplished by implementing the Comparable interface. Next TopicJava PriorityQueue class |
Lớp TreeSet trong java implements giao diện Set sử dụng cấu trúc cây để lưu trữ các phần tử. Nó kế thừa lớp AbstractSet và implements giao diện NavigableSet. Các đối tượng của lớp TreeSet được lưu trữ theo thứ tự tăng dần.
Các điểm quan trọng về lớp TreeSet trong java là:
- Chỉ chứa các phần tử duy nhất giống như HashSet.
- Thời gian truy xuất nhanh.
- Duy trì thứ tự tăng dần.
Nội dung chính
Keywords searched by users: treeset class in java
Categories: Chi tiết 49 Treeset Class In Java
See more here: kientrucannam.vn
See more: https://kientrucannam.vn/vn/