Dark Horse programmer--java--Customize a comparer to sort the elements in the TreeSet collection by the specified method

Source: Internet
Author: User







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

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.