Sort each object element in the list in chronological order

Source: Internet
Author: User
Tags comparable static class
Object sorting

A problem has been encountered in the work:

Call the interface of someone's home to query the database, but the results of the query in the interface do not sort the results by time. So I used a method to sort the result set of the query according to the time. My project class structure is complex, I use a simple user class to demonstrate the sorting process, but also hope to understand.


Import Java.text.SimpleDateFormat;

Import java.util.*;
        public class Listsort {public static class UserBean {private String ID;

        Private String birthday;
        Public String GetId () {return id;
        public void SetId (String id) {this.id = ID;
        Public String Getbirthday () {return birthday;
        } public void Setbirthday (String birthday) {this.birthday = birthday; 
        } public static void Main (string[] args) {list<userbean> List = new arraylist<userbean> ();
        Userlistgenerate (list);

        System.out.println ("Sort before:" +list);
        Listsort (list);
    System.out.println ("Sort after:" +list);
        private static void Userlistgenerate (List<userbean> List) {UserBean user1 = new UserBean ();
        UserBean user2 = new UserBean ();
        UserBean User3 = new UserBean ();
        User1.setid ("Zhagnsan"); User1.setBirthday ("1980-11-01");
        User2.setid ("Lisi");

        User2.setbirthday ("1981-12-01");
        User3.setid ("Wangwu");

        User3.setbirthday ("1980-12-01");
        List.add (user1);
        List.add (User2);
    List.add (USER3); } private static void Listsort (List<userbean> list) {Collections.sort (list, new Comparator<userbean  > () {@Override public int compare (UserBean O1, UserBean O2) {SimpleDateFormat
                format = new SimpleDateFormat ("Yyyy-mm-dd");
                    try {Date dt1 = Format.parse (O1.getbirthday ());
                    Date DT2 = Format.parse (O2.getbirthday ());
                    if (Dt1.gettime () > Dt2.gettime ()) {return 1;
                    else if (Dt1.gettime () < Dt2.gettime ()) {return-1;
                    else {return 0; catch (excEption e) {e.printstacktrace ();
            return 0;
    }
        }); }
}


The above is sort the list collection based on the time in the object. Expand

Comparator is an interface that overrides the Compare () and Equals () for the parity function, or null, using the default order of elements, such as A,b,c,d,e,f,g, which is a,b,c,d,e,f,g, Of course the numbers are the same.
Compare (A,b) method: Returns a negative integer, 0, or positive integer, respectively, based on the first argument being less than, equal to, or greater than the second argument.
Equals (obj) method: Returns True only if the specified object is also a Comparator and enforces the same sort as this Comparator.

Collections.sort (list, new Pricecomparator ()); The second argument returns a value of int, which is equivalent to a flag that tells the sort method to sort the list in what order.

The specific implementation code method is as follows:

Book Entity class:

    Package com.tjcyjd.comparator;  
    Import Java.text.DecimalFormat;  
    Import Java.text.SimpleDateFormat;  
    Import Java.util.GregorianCalendar;  
    Import Java.util.Iterator;  
      
    Import Java.util.TreeMap; /** * * @author YJD * * * * * * * */public class book implements comparable {//definition named Boo Class of K, which inherits from the object class public int id;//number public String name;//name public double, by default; Price private String author;//author public gregoriancalendar calendar;//publication date public Bo  
        Ok () {This (0, "X", 0.0, New GregorianCalendar (), ""); public book (int ID, string name, double price, GregorianCalendar calender, String aut  
            Hor) {this.id = ID;  
            THIS.name = name;  
            This.price = Price;  
            This.calendar = calender;  
        This.author = author;  
      
   }     Overrides a method that inherits from the parent object, satisfies the requirements of the book Class information description public String toString () {string showstr = id + ' \ t ' + NA Me Defines the string DecimalFormat Formatprice = new DecimalFormat ("0.00") that displays class information;//Format the price to two digits after the decimal point Showstr +  
            = "\ T" + formatprice.format (price);//formatted prices SHOWSTR + = "T" + author;  
            SimpleDateFormat formatdate = new SimpleDateFormat ("YYYY year mm month DD Day"); Showstr + = "T" + Formatdate.format (Calendar.gettime ()); Format time return showstr; Return class information string} public int compareTo (Object obj) {//comparable interface method Book B = (Boo  
            k) obj; return this.id-b.id; Compare size by Book ID, for default sort} public static void Main (string[] args) {Books B1 = new  
            (10000, "dream of Red Mansions", 150.86, New GregorianCalendar (2009, 01, 25), "Cao Xueqin, Gao E");  
       Book b2 = new book (10001, "The Kingdoms", 99.68, New GregorianCalendar (2008, 7,             8), "Luo Guan Zhong");  
            Book B3 = new book (10002, "Outlaws of the Marsh", 100.8, New GregorianCalendar (2009, 6, 28), "Nai");  
            Book B4 = new book (10003, "Journey to the Westward", 120.8, New GregorianCalendar (2011, 6, 8), "en");  
            Book B5 = new (10004, "Tianlong Eight", 10.4, New GregorianCalendar (2011, 9, 23), "Sohu");  
            TREEMAP TM = new TreeMap ();  
            Tm.put (B1, new Integer (255));  
            Tm.put (B2, New Integer (122));  
            Tm.put (B3, New Integer (688));  
            Tm.put (B4, new Integer (453));  
            Tm.put (B5, New Integer (40));  
            Iterator it = Tm.keyset (). iterator ();  
            Object key = null, value = NULL;  
            book BB = null;  
                while (It.hasnext ()) {key = It.next ();  
                bb = (book) key;  
                Value = Tm.get (key);  
System.out.println (bb.tostring () + "T inventory:" + tm.get (key));            }  
        }  
    }   

Custom comparer and test classes:

    Package com.tjcyjd.comparator;  
    Import java.util.ArrayList;  
    Import java.util.Collections;  
    Import Java.util.Comparator;  
    Import Java.util.GregorianCalendar;  
    Import Java.util.Iterator;  
      
    Import java.util.List; public class Usecomparator {public static void main (String args[]) {list<book> List = new Arraylist<book> (); Array sequence Book B1 = new book (10000, "dream of Red Mansions", 150.86, New GregorianCalendar (2009, 01, 25),  
            "Cao Xueqin, Gao-e");  
            Book b2 = new book (10001, "The Chinese Kingdoms", 99.68, New GregorianCalendar (2008, 7, 8), "Luo Guan");  
            Book B3 = new book (10002, "Outlaws of the Marsh", 100.8, New GregorianCalendar (2009, 6, 28), "Nai");  
            Book B4 = new book (10003, "Journey to the Westward", 120.8, New GregorianCalendar (2011, 6, 8), "en");  
        Book B5 = new (10004, "Tianlong Eight", 10.4, New GregorianCalendar (2011, 9,            23), "Sohu");  
            List.add (B1);  
            List.add (B2);  
            List.add (B3);  
            List.add (B4);  
            List.add (B5); Collections.sort (list);  
            No default comparer, cannot sort System.out.println (elements in array sequence:);  
            Myprint (list); Collections.sort (list, new Pricecomparator ());  
            Sort System.out.println According to Price ("sorted by book Price:");  
            Myprint (list); Collections.sort (list, new Calendarcomparator ());  
            Sort System.out.println According to time ("sorted by book Publication Time:");  
        Myprint (list); ///Custom method: The elements in the print output list of the branch public static void Myprint (List<book> list) {Ite Rator it = List.iterator ();  Gets an iterator that iterates through all the elements in the list while (It.hasnext ()) {//If there are elements in the iterator, returns true System.out.println ("\ t" + It.next ()),//Show This element}}//Custom comparer: Sort static class by book Price Pricecomparat OrImplements Comparator {public int compare (object Object1, Object object2) {//implement method in interface Bo Ok p1 = (book) Object1;  
                Cast book P2 = (book) Object2;  
            return new double (p1.price). CompareTo (new double (P2.price));  
            ///Custom Comparer: Sort static class Calendarcomparator implements Comparator {by book publishing time public int Compare (object Object1, Object object2) {//Implementation interface method book P1 = (book) Object1;//Mandatory  
                Convert book P2 = (book) Object2;  
            Return P2.calendar.compareTo (P1.calendar);   }  
        }  
    }




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.