(reproduced) Java list sort

Source: Internet
Author: User
Tags comparable ming

1. Introduction

The sorting of this and the array is not the same.

In fact, Java for the array and list of the order has been implemented, for the array , you can directly use arrays.sort, for list and vector , you You can use the Collections.sort method .

The Java API provides 2 methods for sorting collection types:

Java.util.Collections.sort (java.util.List) java.util.Collections.sort (java.util.List, Java.util.Comparator)

If the elements inside the collection are all of the same type, and the comparable interface is implemented, the first method can be called directly.

If you have other sorts of ideas, such as you don't want to follow the natural order, you can also pass a comparator past, such as reverse.

Elements that are not the same are more complex and can be considered temporarily.

2, by implementing the comparable interface to achieve list sorting

If we now have a list of the person class, to sort by an order property, we can let the person class implement the comparable interface and rewrite its CompareTo method. The specific implementation is as follows:

1), Person entity class

 Public classPersonImplementsComparable<person> {    PrivateString name; PrivateInteger Order; /**     * @returnThe name*/     PublicString GetName () {returnname; }     /**     * @paramName * The name to set*/     Public voidsetName (String name) { This. Name =name; }     /**     * @returnThe order*/     PublicInteger GetOrder () {returnorder; }     /**     * @paramOrder * The order to set*/     Public voidSetorder (Integer order) { This. Order =order; } @Override Public intcompareTo (person arg0) {return  This. GetOrder (). CompareTo (Arg0.getorder ());//Here you define the rules of your sort.     } }

By overriding the CompareTo method of the comparable interface, you can have the program sort by the arrangement we want, such as: Here I have the person sort in ascending order property.

2), test class

 Public Static voidMain (string[] args) {//Initializing DataList<person> ListA =NewArraylist<person>(); Person P1=NewPerson (); Person P2=NewPerson (); Person P3=NewPerson (); P1.setname ("Name1"); P1.setorder (1); P2.setname ("Name2"); P2.setorder (2); P3.setname ("Name3"); P3.setorder (3);    Lista.add (p2);    Lista.add (p1);    Lista.add (p3); //SortCollections.sort (ListA); //print a sorted person     for(person P:lista) {System.out.println (P.getname ()); }}

3), Results:

Name1name2name3

3, by overloading the Collections.sort method

Directly overloads the Java.util.Collections.sort (Java.util.List, Java.util.Comparator) method. We can flexibly modify the way we sort, specifically implemented as follows:

1), Person entity class

Same as the above class, but not implemented comparable interface

 Public classPerson {PrivateString name; PrivateInteger Order; /**     * @returnThe name*/     PublicString GetName () {returnname; }     /**     * @paramName * The name to set*/     Public voidsetName (String name) { This. Name =name; }     /**     * @returnThe order*/     PublicInteger GetOrder () {returnorder; }     /**     * @paramOrder * The order to set*/     Public voidSetorder (Integer order) { This. Order =order; } }

2), test class

 Public Static voidMain (string[] args) {List<Person> ListA =NewArraylist<person>(); Person P1=NewPerson (); Person P2=NewPerson (); Person P3=NewPerson (); P1.setname ("Name1"); P1.setorder (1); P2.setname ("Name2"); P2.setorder (2); P3.setname ("Name3"); P3.setorder (3);        Lista.add (p2);        Lista.add (p1);                 Lista.add (p3); //Add our collation directly hereCollections.sort (ListA,NewComparator<person>() {             Public intCompare (person arg0, person arg1) {returnArg0.getorder (). CompareTo (Arg1.getorder ());                 }        });  for(person P:lista) {System.out.println (P.getname ()); }    }

As seen from the above, a comparator interface is rewritten directly in the Conllections.sort () method, and different sorting methods for the person collection can be used in different places. As in ascending order with the person's order attribute, I just rewrite the method and I can sort my list collection in other places according to other rules, but the code looks more cumbersome than the previous one.

3), results

Name1name2name3

   Thanks: Thank you for reading!

4. Extension: Sort by two fields

For example, first sort by name, if the name is the same, sort by nickname, examples are as follows:

 PackageCom.cy.model;Importjava.util.ArrayList;Importjava.util.Collections;Importjava.util.List; Public classStudentImplementsComparable<student>{    Private intID; PrivateString name;//name    PrivateString sname;//Nickname         Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString Getsname () {returnsname; }     Public voidsetsname (String sname) { This. sname =sname; }     PublicStudent (intID, string name, String sname) {        Super();  This. ID =ID;  This. Name =name;  This. sname =sname; } @Override PublicString toString () {return"Student [id=" + ID + ", name=" + name + ", sname=" +sname+ "]"; }    /*** Student Class sorting method * First Sort by name, if name is the same according to Sname sort*/@Override Public intcompareTo (Student o) {intR1 = This. GetName (). Comparetoignorecase (O.getname ()); intr2 = This. Getsname (). Comparetoignorecase (O.getsname ()); returnR1>0?1: R1<0?-1: R2>0?1: R2<0?-1:0; }        //Test Program     Public Static voidMain (string[] args) {Student S1=NewStudent (2, "Zhangsan", "Z"); Student S2=NewStudent (1, "Zhangsan", "B"); Student S3=NewStudent (3, "Zhangsan", "Y"); Student S4=NewStudent (0, "Lisi", "s"); Student S5=NewStudent (5, "Wangwu", "W"); Student S6=NewStudent (x, "Wangwu", "XX"); Student S7=NewStudent (8, "aming", "Ming"); List<Student> list =NewArraylist<student>();        List.add (S1); List.add (S2); List.add (S3); List.add (S4);                List.add (S5); List.add (S6); List.add (S7);                Collections.sort (list);  for(Student s:list) {System.out.println (s); }    }    }

Print:

Student [Id=8, name=aming, sname=ming]student [id=0, name=lisi, sname=s]student [id=5, NAME=WANGWU, Sname=w]student [ID =10, NAME=WANGWU, sname= xx]student[ID =1, Name=zhangsan, sname=b]student [ID =3, Name=zhangsan, sname=y]student [id=2, Name=zhangsan, Sname=z]

(reproduced) Java list sort

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.