We know that set set can hold a series of objects, such as Int,class, and are unordered and non-repeatable. Today we are going to discuss:set can be sorted, how to customize the collation
First, steal a graph to illustrate the inheritance relationship of set:
Today we mainly discuss the usage of sortedset.
(Note: All are excuses, need to use their implementation class)
Let's implement the SortedSet sort:
public class test { Span class= "Hljs-keyword" >public static void main (string[] args) {treeset<string> set< /span>=new treeset<string> (); set . Add ( "B" ); set . Add ( "D" ); set . Add ( "A" ); set . Add ( "E" ); set . Add ( "C" ); System. out . println (set ); }}
What is the result, [A, B, C, D, E] ....
is in alphabetical order, so if I want it to be in a flashback, you need to customize a collation.
//这时TreeSet的一个构造方法//comparator:这个就是自定义的排序规则publicTreeSetsuper E> comparator) { this(new TreeMap<>(comparator)); }
Let's test it out.
Public classTest { Public Static void Main(string[] args) {//new a custom comparatorTreeset<string>Set=NewTreeset<string> (NewMycomparator ());Set. Add ("B");Set. Add ("D");Set. Add ("A");Set. Add ("E");Set. Add ("C"); System. out. println (Set); }}class Mycomparator implements comparator{@Override Public int Compare(Object O1, Object O2) {string s1= (string) O1; String s2= (String) O2;//reverse order returnS2.compareto (S1); }}
Results and obviously: [E, D, C, B, A]
This is all very simple, if we use a custom class, such as a person class, to order by age, let's look at how to implement:
Public classTest { Public Static void Main(string[] args) {//Custom collationTreeset<person>Set=NewTreeset<person> (NewMycomparator ());Set. Add (NewPerson ("A", -));Set. Add (NewPerson ("D",Ten));Set. Add (NewPerson ("E", +));Set. Add (NewPerson ("C", -));Set. Add (NewPerson ("B", -)); System. out. println (Set); }}class person{String name;intAge Public Person(String name,intAge) { This. name=name; This. age=age; } @Override//Rewrite the ToString method to make the output format: PublicStringtoString() {return "Name:"+name+", age="+age; }}class Mycomparator implements comparator{@Override Public int Compare(Object O1, Object O2) {person p1= (person) O1; Person p2= (person) O2;//Custom comparison rules return(int) (P1.age-p2.age); }}
Results:
[Name:d,age=10, Name:a,age=20, name:b,age=30, name:e,age=40, name:c,age=50]
Achieve the results we want.
So we're done with the sort of set.
SortedSet Custom Sorting