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