Read Line of Text Input by User and Place Each Word in a Treeset Java
TreeSet is one of the well-nigh 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.
Information technology 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 grade.
It can clearly be perceived from the above image that the navigable set extends the sorted gear up interface. Since a set doesn't retain the insertion guild, the navigable ready interface provides the implementation to navigate through the Fix. The class which implements the navigable set up is a TreeSet which is an implementation of a cocky-balancing tree. Therefore, this interface provides us with a way to navigate through this tree.
Note:
- An object is said to exist comparable if and only if the respective class implements a Comparable interface.
- String class and all the Wrapper classes already implement Comparable interface simply StringBuffer course implements Comparable interface. Hence, we DO Non get a ClassCastException in the above example.
- For an empty tree-set, when trying to insert null as the first value, 1 will go NPE from JDK 7. From JDK 7 onwards, null is non at all accustomed by TreeSet. However, up to JDK 6, zip was accepted equally the beginning value, but any insertion of more than null values in the TreeSet resulted in NullPointerException. Hence, information technology was considered a bug and thus removed in JDK 7.
- TreeSet serves as an fantabulous choice for storing large amounts of sorted information which are supposed to exist accessed quickly because of its faster access and retrieval time.
- The insertion of zilch values into a TreeSet throws NullPointerException considering while insertion of zip, information technology gets compared to the existing elements, and zippo cannot exist compared to any value.
How does TreeSet work Internally?
TreeSet is basically an implementation of a cocky-balancing binary search tree like a Cherry-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 certain that the height of the tree is always O(log(N)) for all the operations. Therefore, this is considered equally i of the most efficient data structures in order to store the huge sorted data and perform operations on it. Withal, operations like printing N elements in the sorted order accept O(N) time.
Now let united states hash out 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 prepare. If no such object exists, the set should be "wrapped" using the Collections.synchronizedSortedSet method. This is best washed at the creation time, to forbid adventitious unsynchronized admission to the set. It can be accomplished as shown below equally follows:
TreeSet ts = new TreeSet(); Gear up 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 form. The TreeSet class consists of various constructors which allow the possible cosmos of the TreeSet. The following are the constructors bachelor in this course:
- 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, so, 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 demand an external specification of the sorting order.
Syntax: If we wish to create an empty TreeSet with the proper noun 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 drove in which elements will get stored in default natural sorting order. In short, this constructor is used when whatsoever conversion is needed from any Drove object to TreeSet object.
Syntax: If we wish to create a TreeSet with the name ts, then, it can exist 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 volition get stored in default natural sorting order. In short, this constructor is used to catechumen the SortedSet object to the TreeSet object.
Syntax: If we wish to create a TreeSet with the proper name ts, then, it tin exist created as follows:
TreeSet t = new TreeSet(SortedSet s);
Methods in TreeSet Class are depicted below in tabular format which later on on we will be implementing to showcase in the implementation part.
TreeSet implements SortedSet and then it has the availability of all methods in Collection, Fix, and SortedSet interfaces. Following are the methods in the Treeset interface. In the table beneath, the "?" signifies that the method works with whatever type of object including user-defined objects.
Method | Description |
---|---|
add(Object o) | This method will add the specified element co-ordinate to the same sorting guild mentioned during the creation of the TreeSet. Duplicate entries will not become added. |
addAll(Collection c) | This method volition add all elements of the specified Collection to the set. Elements in the Collection should exist homogeneous otherwise ClassCastException will be thrown. Duplicate Entries of Collection volition not be added to TreeSet. |
ceiling?(East eastward) | This method returns the least element in this gear up greater than or equal to the given chemical element, or null if there is no such chemical element. |
clear() | This method will remove all the elements. |
clone() | The method is used to return a shallow copy of the prepare, which is just a simple copied set. |
Comparator comparator() | This method will render the Comparator used to sort elements in TreeSet or information technology volition return null if the default natural sorting gild 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 guild. |
descendingSet?() | This method returns a opposite order view of the elements contained in this set. |
offset() | 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 chemical element in this set less than or equal to the given element, or null if in that location is no such chemical element. |
headSet(Object toElement) | This method will render elements of TreeSet which are less than the specified chemical element. |
higher?(E e) | This method returns the to the lowest degree element in this gear up 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 simulated for the opposite instance. |
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 information technology will throw NoSuchElementException. |
lower?(E east) | This method returns the greatest element in this set strictly less than the given chemical element, or null if there is no such element. |
pollFirst?() | This method retrieves and removes the first (lowest) element, or returns null if this fix is empty. |
pollLast?() | This method retrieves and removes the last (highest) element, or returns null if this fix is empty. |
remove(Object o) | This method is used to render a specific element from the ready. |
size() | This method is used to render the size of the ready or the number of elements nowadays in the set. |
spliterator() | This method creates a belatedly-bounden 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 sectional. |
tailSet(Object fromElement) | This method will render elements of TreeSet which are greater than or equal to the specified element. |
Illustration: The post-obit implementation demonstrates how to create and use a TreeSet.
Java
import
java.util.*;
class
GFG {
public
static
void
chief(String[] args)
{
Set<String> ts1 =
new
TreeSet<>();
ts1.add together(
"A"
);
ts1.add together(
"B"
);
ts1.add(
"C"
);
ts1.add(
"C"
);
Arrangement.out.println(ts1);
}
}
Implementation:
Here we volition be performing various operations over the TreeSet object to go 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 every bit follows:
- Adding elements
- Accessing elements
- Removing elements
- Iterating through elements
At present let us discuss each operation individually one by one later alongside grasping with the assist of a clean java programme.
Performance 1: Calculation Elements
In order to add an element to the TreeSet, we can use the add() method. Notwithstanding, the insertion society is not retained in the TreeSet. Internally, for every element, the values are compared and sorted in ascending social club. Nosotros demand to keep a annotation that duplicate elements are not allowed and all the duplicate elements are ignored. And besides, Null values are not accustomed by the TreeSet.
Example
Java
import
coffee.util.*;
class
GFG {
public
static
void
master(String[] args)
{
Ready<Cord> ts =
new
TreeSet<>();
ts.add(
"Geek"
);
ts.add(
"For"
);
ts.add together(
"Geeks"
);
System.out.println(ts);
}
}
Output:
[For, Geek, Geeks]
Operation 2: Accessing the Elements
After adding the elements, if we wish to access the elements, we can employ inbuilt methods like contains(), first(), last(), etc.
Example
Java
import
java.util.*;
class
GFG {
public
static
void
master(String[] args)
{
NavigableSet<String> ts =
new
TreeSet<>();
ts.add together(
"Geek"
);
ts.add together(
"For"
);
ts.add together(
"Geeks"
);
System.out.println(
"Tree Gear up is "
+ ts);
String check =
"Geeks"
;
System.out.println(
"Contains "
+ check +
" "
+ ts.contains(check));
System.out.println(
"Commencement Value "
+ ts.kickoff());
System.out.println(
"Terminal Value "
+ ts.last());
String val =
"Geek"
;
System.out.println(
"College "
+ ts.higher(val));
Organisation.out.println(
"Lower "
+ ts.lower(val));
}
}
Output:
Tree Set is [For, Geek, Geeks] Contains Geeks true First Value For Last Value Geeks College Geeks Lower For
Functioning 3: Removing the Values
The values tin exist removed from the TreeSet using the remove() method. There are various other methods that are used to remove the first value or the terminal value.
Case
Java
import
java.util.*;
form
GFG {
public
static
void
primary(String[] args)
{
NavigableSet<String> ts =
new
TreeSet<>();
ts.add(
"Geek"
);
ts.add(
"For"
);
ts.add(
"Geeks"
);
ts.add(
"A"
);
ts.add(
"B"
);
ts.add(
"Z"
);
System.out.println(
"Initial TreeSet "
+ ts);
ts.remove(
"B"
);
Organisation.out.println(
"After removing chemical element "
+ ts);
ts.pollFirst();
System.out.println(
"After removing first "
+ ts);
ts.pollLast();
System.out.println(
"After removing last "
+ ts);
}
}
Output:
Initial TreeSet [A, B, For, Geek, Geeks, Z] After removing element [A, For, Geek, Geeks, Z] Afterwards removing first [For, Geek, Geeks, Z] After removing last [For, Geek, Geeks]
Operation four: Iterating through the TreeSet
At that place are diverse ways to iterate through the TreeSet. The about famous one is to employ the enhanced for loop. and geeks generally you would be iterating the elements with this approach while practicing questions over TreeSet as this is most frequently used when information technology comes to tree, maps, and graphs bug.
Example
Java
import
coffee.util.*;
class
GFG {
public
static
void
main(String[] args)
{
Prepare<String> ts =
new
TreeSet<>();
ts.add(
"Geek"
);
ts.add(
"For"
);
ts.add(
"Geeks"
);
ts.add(
"A"
);
ts.add(
"B"
);
ts.add(
"Z"
);
for
(String value : ts)
System.out.print(value +
", "
);
System.out.println();
}
}
Output:
A, B, For, Geek, Geeks, Z,
Features of a TreeSet:
- TreeSet implements the SortedSet interface. So, indistinguishable values are not immune.
- 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 let the insertion of heterogeneous objects. It will throw a classCastException at Runtime if we try to add heterogeneous objects.
- The TreeSet can merely take generic types which are comparable.
For example, the StringBuffer class implements the Comparable interface
Java
import
java.util.*;
class
GFG {
public
static
void
main(String[] args)
{
Set<StringBuffer> ts =
new
TreeSet<>();
ts.add(
new
StringBuffer(
"A"
));
ts.add(
new
StringBuffer(
"Z"
));
ts.add together(
new
StringBuffer(
"50"
));
ts.add(
new
StringBuffer(
"B"
));
ts.add(
new
StringBuffer(
"O"
));
ts.add(
new
StringBuffer(
one
));
System.out.println(ts);
}
}
Source: https://www.geeksforgeeks.org/treeset-in-java-with-examples/
Post a Comment for "Read Line of Text Input by User and Place Each Word in a Treeset Java"