Chapter Topic: In this chapter, a brief review of the Java collection Collections.sort method is made.
package test;/** * @author Yshuai * @version creation time:2014-08-20 am 09 :49:36 */import java.util.arraylist;import java.util.collections;import java.util.comparator;import java.util.list;public class sorttest {public static Void main (String[] args) {List<String> lists = new ArrayList< String> (); List<a> list = new arraylist<a> (); List<b> listb = new arraylist<b> (); Lists.add ("5"); Lists.add ("2"); Lists.add ("9" ); Collections.sort (lists); System.out.println ("Object string in// lists itself contains compareto methods, so you can call the sort method directly, sort by natural order, ascending sort" + lists);// Initialize Lista method a aa = new a (); Aa.setname ("AA"); Aa.setorder (1); A bb = new a (); Bb.setname ("BB"); Bb.setorder (2); List.add (BB); List.add (AA); Collections.sort (list); SYSTEM.OUT.PRINTLN ("Set your CompareTo method in your Java entity class" + liST);// initializes the Listb method, B does not implement the CompareTo method, please pass a collections method among Collections.sort methods CompareTo = new b (); Ab.setname ("AB"); Ab.setorder ("1"); B ba = new b (); Ba.setname ("ba"); Ba.setorder ("2"); Listb.add (BA); Listb.add (AB);// Implement Collections.sort (Listb, new comparator<b> () {@Overridepublic based on the Collections.sort overloaded method int compare (B&NBSP;B1,&NBSP;B&NBSP;B2) {return b1.getorder (). CompareTo (B2.getOrder ());}); System.out.println (LISTB);}} Class a implements comparable<a> {private string name;private integer order;public string getname () {return name;} Public void setname (String name) {this.name = name;} Public integer getorder () {return order;} Public void setorder (Integer order) {this.order = order;} @Overridepublic string tostring () {return "Name is " + name + " order is " + order;} @Overridepublic int compareto (a a) {return this.order.compareto (A.getorder ());}} class b {private string name;private string order;public string GetName () {return name;} Public void setname (String name) {this.name = name;} Public string getorder () {return order;} Public void setorder (String order) {this.order = order;} @Overridepublic string tostring () {return "name is " + name + " order is " + order;}}
Writing background: Because of the real-time sort function of storm in the current business. Here is a brief review of the Java Foundation and a deepening of it.
Summary There are two simple ways to sort the process:
1 Implement a good CompareTo method, at which point the Collection.sort method will invoke the Bean object in the run
2 If you do not implement it, you need to specify a comparer for the sort method.
Simpletips