customize a comparer to sort the elements in the TreeSet collection by the specified method
Import java.util.comparator;import java.util.iterator;import java.util.treeset;//Customize a comparator class Mycompare implements comparator{@Overridepublic int Compare (object O1, Object O2) {//TODO auto-generated method stubminstudent ms1= (Minstuden t) O1; Minstudent ms2= (minstudent) O2;int i=ms1.getname (). CompareTo (Ms2.getname ()); if (i==0) return ms1.getage ()-ms2.getage (); return i;}} public class Mycomparedemos {public static void main (string[] args) {//TODO auto-generated method Stubtreeset ts = new Tr Eeset (New Mycompare ()), Ts.add (New Minstudent ("CCC"), Ts.add (New Minstudent ("ddd", ""), Ts.add (New Minstudent (" AAA ("Ts.add"); (New Minstudent ("Dad"), Ts.add (New Minstudent ("fff"); Ts.add (New Minstudent ("SSS", 22)); Ts.add (New Minstudent ("JJJ")); Iterator it = Ts.iterator (); while (It.hasnext ()) {minstudent ms = (minstudent) it.next ( ); System.out.println (Ms.tostring ());}}}
Class Minstudent implements Comparable{public int getname;private String name;p rivate int age; Minstudent (String name, int age) {this.name = name; this.age=age;} public int getage () {return age;} Public String GetName () {return name;} Public String toString () {return ' name: ' +name + '---age ' +age;} @Overridepublic int compareTo (Object o) {//Minstudent s = (minstudent) o;//first sorted by age int I=this.getage ()-s.getage (); if (i = = 0) return This.getname (). CompareTo (S.getname ()); return i;}}
before the comparer is used, the order of elements in the collection is
after using the comparator:
Dark Horse programmer--java--Customize a comparer to sort the elements in the TreeSet collection by the specified method