How to Read Text File to Treeset and Display Number of Duplicate Java

A TreeSet in Coffee is another important implementation of the Fix interface that is similar to the HashSet class, with one added comeback.

It sorts elements in ascending social club while HashSet does not maintain any order.

Java TreeSet implements SortedSet interface. Information technology is a collection for storing a fix of unique elements (objects) co-ordinate to their natural ordering.

It creates a sorted collection that uses a tree structure for the storage of elements or objects. In simple words, elements are kept in sorted, ascending club in the tree set.

For example, a prepare of books might be kept by height or alphabetically by title and author.

TreeSet in Java

In Java TreeSet, access and retrieval of elements are quite fast because of using tree structure. Therefore, TreeSet is an excellent selection for quick and fast access to big amounts of sorted information.

The only restriction with using tree set is that nosotros cannot add duplicate elements in the tree set.

TreeSet class declaration in Java


TreeSet is a generic class that is alleged every bit:

          grade TreeSet<T>

In this syntax, T defines the type of objects or elements that the fix will hold.

Bureaucracy of TreeSet form in Java


TreeSet grade extends AbstractSet and implements NavigableSet interface. NavigableSet extends SortedSet to provide navigation methods.

TreeSet hierarchy in Java

Features of TreeSet class in Java


At that place are several important features of TreeSet grade in java that must exist kept in listen. They are as:

1. Java TreeSet contains unique elements similar to the HashSet. It does not allow the addition of a duplicate chemical element.

2. The access and retrieval times are quite fast.

3. TreeSet does not allow inserting zilch element.

4. TreeSet class is non-synchronized. That means it is not thread-safety.

5. TreeSet maintains the ascending social club. When we add together elements into the collection in whatsoever order, the values are automatically presented in sorted, ascending society.

half dozen. Java TreeSet internally uses a TreeMap for storing elements.

How to create TreeSet in Java?


TreeSet has the following constructors. We can create a TreeSet instance by using i of its four constructors.

1. TreeSet( ): This default constructor creates an empty TreeSet that volition be sorted in ascending order according to the natural society of its elements.

ii. TreeSet(Drove c): It creates a tree set and adds the elements from a collection c according to the natural ordering of its elements. All the elements added into the new prepare must implement Comparable interface.

If collection c's elements do not implement Comparable interface or are non mutually comparable, this constructor throws ClassCastException.

If collection c contains null reference, this constructor throws NullPointerException.

3. TreeSet(Comparator comp): This constructor creates an empty tree gear up that will exist sorted co-ordinate to the comparator specified by comp.

All elements in the tree set are compared mutually by the specified comparator. A comparator is an interface that is used to implement the ordering of data.

4. TreeSet(SortedSet south): This constructor creates a tree gear up that contains the elements of sorted fix s.

Important TreeSet Methods in Java


TreeSet class in java provides a variety of methods to perform unlike tasks. They are every bit follows:

1. boolean add(Object o): This method is used to add the specified element to this ready if it is not already present.

ii. boolean addAll(Collection c): This method is used to add together all the elements of the specified drove to the set.

three. void articulate(): It is used to remove all the elements from the set.

iv. boolean isEmpty(): This method is used to cheque that the set has elements or not. It returns true if the set contains no elements otherwise returns faux.

v. boolean remove(Object o): This method is used to remove the specified element from the set up if information technology is present.

6. boolean contains(Object o): It returns true if the set has the specified element otherwise returns false.

seven. int size(): This method is used to get the total number of elements in the ready.

8. Iterator iterator(): The iterator() method is used to iterate the elements in ascending order.

9. Spliterator spliterator(): The splititerator() method is used to create a late-bounden and neglect-fast spliterator over the elements in the tree set.

ten. Object clone(): The clone() method is used to get a shallow copy of this TreeSet instance.

11. Iterator descendingIterator(): It is used to iterate the elements in descending order.

Important Methods Divers by SortedSet Interface


Since Java TreeSet implements SortedSet interface, all the methods divers by SortedSet interface tin can be used while using TreeSet class. They are as:

ane. Object first(): It is used to get the first (everyman) element currently in the sorted prepare.

two. Object last(): This method returns the last (highest) element currently in the sorted ready.

3. Comparator comparator(): It returns comparator that is used to order elements in the set. If the TreeSet uses the natural ordering, this method returns null.

4. SortedSet headSet(Object toObject): This method returns the collection of elements that are less than the specified element.

5. SortedSet subSet(Object fromElement, Object toElement): It returns elements from the set that lie between the given range in which fromElement is included and toElement is excluded.

6. SortedSet tailSet(Object fromElement): Information technology returns elements from the ready that is greater than or equal to the specified chemical element.

Of import Methods Defined past NavigableSet Interface


Since Java TreeSet Class implements NavigableSet interface, therefore, all methods of this interface can be used while using tree ready class. They are every bit:

1. Object ceiling(Object o): It returns the lowest element from the set equal to or greater than the specified element. If no such element is found, information technology returns zippo.

2. Object flooring(Object o): It returns the greatest element from the set equal to or less than the specified chemical element. If no such element is found, information technology returns null element.

3. Object lower(Object o): This method returns the largest element from the set strictly less than the specified element. If no such element is found, it will return zip element.

4. Object higher(Object o): This method returns the smallest element from the set strictly greater than the specified element. If no such element is found, it will return null element.

5. Object pollFirst(): It is used to remove and retrieve the beginning element in the tree gear up.

6. Object pollLast(): It is used to remove and retrieve the concluding chemical element in the tree ready.

vii. NavigableSet descendingSet(): This method returns elements in reverse guild.

8. NavigableSet headSet(Object toObject, boolean inclusive): This method returns the collection of elements that are less than or equal to (if, inclusive is truthful) the specified element.

9. NavigableSet subSet(Object fromElement, boolean fromInclusive, Object toElement, boolean toInclusive): This method returns elements from the set that lie between the specified range.

10. NavigableSet tailSet(Object fromElement, boolean inclusive): It returns elements from the ready that is greater than or equal to (if, inclusive is true) the specified element.

Java TreeSet Example Programs


Permit's take different types of example programs based on the above methods defined by TreeSet, SortedSet, and NavigableSet.

Let's create a program where we will perform unlike operations such as calculation, checking the size of TreeSet, and the set is empty or non. Look at the source lawmaking to understand improve.

Program source code 1:

import java.util.Set; import java.util.TreeSet; public course TreeSetEx1 { public static void chief(Cord[] args)  { // Create a tree ready.	  Set<String> ts = new TreeSet<>();  // Check Gear up is empty or not.   boolean empty = ts.isEmpty();   Arrangement.out.println("Is TreeSet empty: " +empty);    // Checking the size of TreeSet before adding elements into it.   int size = ts.size();   System.out.println("Size of TreeSet: " +size);  // Adding elements into TreeSet.    ts.add("India"); // ts.size() is 1.    ts.add("USA"); // ts.size() is two.    ts.add("Australia"); // ts.size() is iii.    ts.add("New zealand"); // ts.size() is four.    ts.add("Switzerland"); // ts.size() is 5.        System.out.println("Sorted TreeSet: " +ts);    int size2 = ts.size(); System.out.println("Size of TreeSet afterwards adding elements: " +size2);   } }
Output:       Is TreeSet empty: truthful       Size of TreeSet: 0       Sorted TreeSet: [Australia, Bharat, New zealand, Switzerland, Usa]       Size of TreeSet later adding elements: 5        

Let's make a program where we will perform operations similar removing an element and checking of a specific chemical element.

Program source code ii:

import java.util.TreeSet; public class TreeSetEx2  { public static void main(String[] args)  {  TreeSet<Cord> ts = new TreeSet<>();  // Add together Strings to tree ready.   ts.add("India");   ts.add("Us");   ts.add("Commonwealth of australia");   ts.add together("New zealand");   ts.add("Switzerland");    // Checking for a specific element in gear up.   boolean chemical element = ts.contains("United states of america");   System.out.println("Is Usa in TreeSet: " +element);  // Removing element from the tree ready.    ts.remove("New zealand");    System.out.println("Sorted tree set up: " +ts);    ts.articulate();    System.out.println("Elements in tree set: " +ts);   } }
Output:        Is USA in TreeSet: true        Elements in tree ready: [Australia, India, Switzerland, Usa]        Elements in tree set up: []        

Now we will make a program to perform different operations based on methods defined by the SortedSet interface. Expect at the source code.

Program source code 3:

import java.util.HashSet; import java.util.Set up; import java.util.SortedSet; import java.util.TreeSet; public grade TreeSetEx3 { public static void main(String[] args)  {  Fix<Cord> s = new HashSet<>();   s.add("Delhi");   s.add("New York");   s.add together("Paris");   southward.add("London");   s.add("Delhi"); // Adding indistinguishable elements.    TreeSet<String> ts = new TreeSet<>(south); System.out.println("Sorted TreeSet: " +ts);  // Using methods of SortedSet interface.   Arrangement.out.println("First Element: " +ts.first());   System.out.println("Last Chemical element: " +ts.last());   System.out.println("HeadSet Elements: " +ts.headSet("London"));   System.out.println("TailSet Elements: " +ts.tailSet("London"));    SortedSet<String> subSet = ts.subSet("Delhi", "Paris"); System.out.println("SubSet Elements: " +subSet); System.out.println("Sorted Fix: " +ts.comparator()); // It will return null considering natural ordering is used.   } }
Output:       Sorted TreeSet: [Delhi, London, New York, Paris]       Beginning Chemical element: Delhi       Last Element: Paris       HeadSet Elements: [Delhi]       TailSet Elements: [London, New York, Paris]       SubSet Elements: [Delhi, London, New York]       Sorted Ready: zero

Allow'south take an example program where nosotros will perform operations based on NavigableSet interface methods.

Program source code 4:

import coffee.util.TreeSet; public class TreeSetEx4  { public static void main(String[] args)  { TreeSet<Integer> ts = new TreeSet<>();  ts.add(25);  ts.add together(eighty);  ts.add(05);  ts.add(100);  ts.add(90);  ts.add together(200);  ts.add together(300); System.out.println("Sorted TreeSet: " +ts);  // Using methods of NavigableSet interface.   System.out.println("Largest element less than 100: " +ts.lower(100));   System.out.println("Smallest element greater than 100: " +ts.college(100));   System.out.println("Flooring: " +ts.flooring(85));   System.out.println("Ceiling: " +ts.ceiling(ten));       System.out.println(ts.pollFirst()); // Remove and call up the commencement element from the set.   System.out.println(ts.pollLast()); // Remove and retrieve the last chemical element from the set.   System.out.println("New Treeset: " +ts);      System.out.println("HeadSet: " +ts.headSet(ninety,true));   Arrangement.out.println("SubSet: " +ts.subSet(90, true, 200, true));   } }
Output:       Sorted TreeSet: [5, 25, 80, 90, 100, 200, 300]       Largest element less than 100: 90       Smallest element greater than 100: 200       Floor: 80       Ceiling: 25       5       300       New Treeset: [25, 80, 90, 100, 200]       HeadSet: [25, 80, 90]       SubSet: [90, 100, 200]

How to iterate TreeSet in Java?


In this department, we volition iterate elements of TreeSet using iterator() method in ascending and descending order. Look at the following source code.

Program source lawmaking v:

import java.util.Iterator; import java.util.TreeSet; public class KeySetDemo  { public static void master(Cord[] args)  { TreeSet<Integer> ts = new TreeSet<>();  ts.add together(25);  ts.add(lxxx);  ts.add(05);  ts.add(100);  ts.add together(90);   System.out.println("Sorted TreeSet:"); // Traversing elements.  Iterator<Integer> itr = ts.iterator();     while(itr.hasNext()){      Arrangement.out.println(itr.next());   }   System.out.println("Iterating elements through Iterator in descending order");   Iterator<Integer> it = ts.descendingIterator();   while(information technology.hasNext())   {     System.out.println(it.side by side());    }  } }
Output:       Sorted TreeSet:       5       25       80       90       100       Iterating elements through Iterator in descending social club       100       90       80       25       5        

How to sort TreeSet in Java | Ordering of Elements in TreeSet


A TreeSet in Java determines the lodge of elements in either of two means:

1. A tree set sorts the natural ordering of elements when it implements java.lang.Comparable interface. The ordering produced by comparable interface is called natural ordering. The syntax is given below:

public interface Comparable { public int compareTo(Object o); // Abstract method.  }

The compareTo() method of this interface is implemented past TreeSet class to compare the current element with element passed in as a parameter for the lodge.

If the chemical element argument is less than the current element, the method returns +ve integer, zero if they are equal, or a -ve integer if element argument is greater.

2. TreeSet in Java as well determines the lodge of elements past implementing the Comparator interface. This technique is used when TreeSet form needs to impose a different sorting algorithm regardless of the natural ordering of elements.

The comparator interface provides two methods in which compare() method is more important. The syntax is as follows:

public interface Comparator { public int Compare(Element e1, Element e2); // Abstract method. public boolean equals(Chemical element eastward); // Abstruse methods.  }

The compare() method of this interface accepts two objects (elements) arguments and returns an integer value that specifies their sort order.

This method returns a -ve value when the first element is less than 2nd element, zero if they are equal, or +ve value if the commencement element is greater.

When to Employ TreeSet in Java?


TreeSet can exist used when we want unique elements in sorted society.

Which is better to apply: HashSet or TreeSet?

If you lot want to store unique elements in sorted order then use TreeSet, otherwise, use HashSet with no ordering of elements. This is considering HashSet is much faster than TreeSet.


Hope that this tutorial has covered the basic points of TreeSet in Java with example programs. I promise that you lot will have understood this topic.
Thanks for reading!!!
Adjacent ⇒ Map Interface in Java

⇐ Prev Side by side ⇒

demarcolawen1989.blogspot.com

Source: https://www.scientecheasy.com/2020/10/treeset-in-java.html/

0 Response to "How to Read Text File to Treeset and Display Number of Duplicate Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel