Treeset, Comparator

Source: Internet
Author: User

Threeset can sort objects in the set. When a treeset wants to add an object to the set, it will be inserted into the ordered object sequence.

Threeset comes with a sorting method that specifies the sorting rules for general data. If you want to specify your own sorting method, You have to rewrite the comparator method for a long time.

 

The following is an example of the built-in method sorting of threeset:

The output result is as follows: [a, B, c, d, e, f]

It can be seen that threeset sorts characters internally.

 

Now we define a preson class, which is sorted in ascending order by the score attribute of the person class. Obviously, threeset itself does not know the user's sorting rules, therefore, we need to define a comparator to tell threeset to sort by score.

So how to define a comparator? We need to implement the comparator interface, rewrite its compare method, define its own comparison rules in this method, and finally pass the comparator of the implemented interface to threeset.

 

The following defines a comparator in the person class:

Personcomparator implements the comparator interface and overwrites the compare () method. p1.score-p2.socore indicates ascending order, which in turn means descending order.

 

Finally, we pass the custom comparator to threeset and use the iterator to output the sorted set:

The output result is as follows:

10

20

30

40

 

Treeset, Comparator

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.