1、collection.sort排序
為安仁等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及安仁網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為成都網(wǎng)站制作、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)、安仁網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!
算法底層實際是 將集合轉(zhuǎn)換成array,再執(zhí)行arrays.sort,arrays.sort利用歸并排序,優(yōu)化的快排,timSort等方式。
2、對string類型數(shù)據(jù)排序
public static void collectionSort() { ListunSorted = new ArrayList (); unSorted.add("10"); unSorted.add("99"); unSorted.add("21"); Collections.sort(unSorted); for(String a:unSorted) { System.out.print(a +" "); } }
輸出:10 21 99
3、對javabean類型數(shù)據(jù)排序
(1)方式一
import java.io.Serializable; public class unSortedBean implements Serializable{ private static final long serialVersionUID = 1L; private String name; private String age; private int order; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } }
以下為排序代碼,編譯期就報錯:
public static void javaBeanSort() { ListunSorted = new ArrayList (); unSortedBean a1 = new unSortedBean(); a1.setName("張三"); a1.setAge("24"); a1.setOrder(9); unSorted.add(a1); unSortedBean a2 = new unSortedBean(); a2.setName("李四"); a2.setAge("22"); a2.setOrder(5); unSorted.add(a2); unSortedBean a3 = new unSortedBean(); a3.setName("王五"); a3.setAge("36"); a3.setOrder(10); unSorted.add(a3); Collections.sort(unSorted); }
原因:string實現(xiàn)了comparable接口,而自定義的javabean未實現(xiàn),可以用這種方式排序
Collections.sort(unSorted,new Comparator() { @Override public int compare(unSortedBean arg0, unSortedBean arg1) { // 升敘 return arg0.getOrder()-arg1.getOrder(); } }); for(unSortedBean bean:unSorted) { System.out.print(JSONObject.fromObject(bean)); }
輸出:{"order":5,"name":"李四","age":"22"}{"order":9,"name":"張三","age":"24"}{"order":10,"name":"王五","age":"36"}
(2)方式二
也可以用collections.sort();方式,只需要javabean實現(xiàn)comparable接口
import java.io.Serializable; public class unSortedBean implements Serializable, Comparable{ private static final long serialVersionUID = 1L; private String name; private String age; private int order; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } @Override public int compareTo(unSortedBean arg0) { // TODO 升敘 return this.order-arg0.getOrder(); } }
輸出:{"order":5,"name":"李四","age":"22"}{"order":9,"name":"張三","age":"24"}{"order":10,"name":"王五","age":"36"}
注意:如果order是string型數(shù)字,需要轉(zhuǎn)換成數(shù)字型再比較,否則比較結(jié)果可能不是預期效果。
比如把本文中的order全部換成string型,輸出結(jié)果為
{"order":10,"name":"王五","age":"36"}{"order":5,"name":"李四","age":"22"}{"order":9,"name":"張三","age":"24"}