Sorting Java Collections

Source: Internet
Author: User

1. Sort the list array for the basic data type of the generic wrapper class (Integer,long,double) "

Collections.sort (List List)

Cases

List<long> Musicids =NewArraylist<>(); Musicids.add (0,1l); Musicids.add (1,10l); Musicids.add (1,2l); Musicids.add (1,8l); Musicids.add (1,4l); System. out. println ("before sorting:"+musicids.tostring ()); Collections.sort (Musicids); System. out. println ("after ordering from small to large:"+ musicids.tostring ());

"Run Results"

"2. Sort ordinary objects according to a member variable (such as ID) in the object."

 Public Static voidSort2 () {List<DataResponse> dataresponselist =lists.newarraylist (); Dataresponselist.add (NewDataresponse (1001L,222)); Dataresponselist.add (NewDataresponse (1002L,444)); Dataresponselist.add (NewDataresponse (1003L,111)); Dataresponselist.add (NewDataresponse (1004L,888)); Collections.sort (dataresponselist,  New comparator<dataresponse>() {@Override   public int  Comp Is (Dataresponse O1, Dataresponse O2) {  return  integer.compare (O1.datatype, O2.datatype);    }    }); System. out. println ("Sort by datatype: \ n"+dataresponselist.tostring ()); Collections.sort (dataresponselist,  New comparator<dataresponse>() {@Override   public int  Comp Is (Dataresponse O1, Dataresponse O2) {  return  Double.compare (o1.dataid,o2.dataid);    }    }); System. out. println ("\ n Sort by dataid: \ n"+dataresponselist.tostring ());}Static classdataresponse{Long Dataid;    Integer DataType;  PublicDataresponse () {} PublicDataresponse (Long dataid, Integer dataType) { This. Dataid =Dataid;  This. DataType =DataType; }     PublicLong Getdataid () {returnDataid; }     Public voidSetdataid (Long dataid) { This. Dataid =Dataid; }     PublicInteger Getdatatype () {returnDataType; }     Public voidSetdatatype (Integer dataType) { This. DataType =DataType; } @Override PublicString toString () {return "dataresponse{"+"dataid="+ Dataid +", datatype="+ DataType +'}'; }}

"Run Results"

Sorting Java Collections

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.