The study of TreeSet

Source: Internet
Author: User
Tags java treeset

TreeSet is another popular implementation of the Set interface along with HashSet and Linkedhashset. All these implementations of Set interface is required in different scenarios. If you don ' t want any order of elements and then you can use HashSet. If you want insertion order of elements to is maintained, then use Linkedhashset. If you want elements to being ordered according to some Comparator and then use TreeSet. The common thing of these three implementations is this they don ' t allow duplicate elements.

Understanding: If you do not need the elements in the set to follow a rule, you can use the HashSet collection, when you need to keep the order of the inserted elements, You can use Linkedhashset to assemble. If you need to define compator to sort the elements, you can use TreeSet. The common denominator of these three collections is that they do not allow duplicate elements.

In this article, I has tried to explain and examples of Java TreeSet. One example doesn ' t use Comparator and another example uses Comparator to order the elements. You can go through some basic properties of TreeSet class here.

Java TreeSet Example with No Comparator:

You already know so if you don ' t pass any comparator while creating a TreeSet, elements'll be placed in their natural Ascending order. In this example, we create a TreeSet of integers without supplying any Comparator as this,

New Treeset<integer> ();

Let's add some integer elements to it.

Set.add (+);      Set.add (one);    Set.add (in);      Set.add (7); Set.add (); Set.add (); Set.add (38);

Print these elements and observe the output.

SYSTEM.OUT.PRINTLN (set);      // Output: [7, one, all, at

You can notice that elements is placed in the ascending order.

The whole code for this example is,

 Public classtreesetexample{ Public Static voidMain (string[] args) {//Creating a TreeSet without supplying any ComparatorTreeSet<Integer> set =NewTreeset<integer>(); //Adding elements to TreeSetSet.add (23); Set.add (11); Set.add (41); Set.add (7); Set.add (69); Set.add (18); Set.add (38); //printing elements of TreeSetSystem.out.println (set); //Output: [7, one, all, at    }}

Understanding: By default, when an element is an integer, the element is in ascending order

Java TreeSet Example with Comparator:

In this example, we create one TreeSet by supplying a customized Comparator. In this example, we'll try to create a TreeSet of Student objects ordered in the descending order of the percentage of M Arks they has obtained. That's means, student with highest marks'll be placed at the top.

Let's create ' Student ' class with three fields–id, name andperc_of_marks_obtained.

classstudent{intID;     String name; intperc_of_marks_obtained;  PublicStudent (intID, String name,intperc_of_marks_obtained) {         This. ID =ID;  This. Name =name;  This. perc_of_marks_obtained =perc_of_marks_obtained; } @Override PublicString toString () {returnId+ ":" +name+ ":" +perc_of_marks_obtained; }}

Let's define our own Comparator class "Mycomparator" which compares the marks of both students.

class Implements Comparator<student>{    @Override    publicint  Compare (Student s1, Student S2)    {        if(s1.id = = s2.id        )            {return 0;        }         Else         {            return s2.perc_of_marks_obtained- s1.perc_of_marks_obtained;}}    }

Important Note:treeset doesn ' t use Hashcode () and Equals () methods to compare it ' s elements. It uses compare () (or CompareTo ()) method to determine the equality of both elements. Therefore, I have kept the code which compares II Student objects based on their ID in compare method itself. This removes possible duplicate elements (elements have same ID) from the TreeSet.

Create one TreeSet of ' Student ' objects with ' mycomparator ' as a Comparator.

// instantiating Mycomparator  new//Creating TreeSet with ' Mycomparator ' as Comparator. TreeSet New Treeset<student> (Comparator);

Add some elements of type ' Student ' to this TreeSet.

Set.add (NewStudent (121, "Santosh", 85)); Set.add (NewStudent (231, "Cherry", 71)); Set.add (NewStudent (417, "David", 82)); Set.add (NewStudent (562, "Praveen", 91)); Set.add (NewStudent (231, "Raj", 61));//Duplicate ElementSet.add (NewStudent (458, "John", 76)); Set.add (NewStudent (874, "Peter", 83)); Set.add (NewStudent (231, "Hari", 52));//Duplicate ElementSet.add (NewStudent (568, "Daniel", 89));

Iterate through the TreeSet.

// iterating through TreeSet Iterator<Student> it = while (It.hasnext ()) {    System.out.println (It.next ( ));}

Output would be,

562:praveen:91568:daniel:89121:santosh:85874:peter:83417:david:82458:john:76231:cherry:71

You can notice this student with highest percentage of marks was placed at the top and also duplicate elements was not Allo Wed in the TreeSet.

The study of TreeSet

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.