您好,登錄后才能下訂單哦!
1、collection.sort排序
算法底層實際是 將集合轉換成array,再執行arrays.sort,arrays.sort利用歸并排序,優化的快排,timSort等方式。
2、對string類型數據排序
public static void collectionSort() { List<String> unSorted = new ArrayList<String>(); 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類型數據排序
(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() { List<unSortedBean> unSorted = new ArrayList<unSortedBean>(); 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實現了comparable接口,而自定義的javabean未實現,可以用這種方式排序
Collections.sort(unSorted,new Comparator<unSortedBean>() { @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實現comparable接口
import java.io.Serializable; public class unSortedBean implements Serializable, Comparable<unSortedBean>{ 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型數字,需要轉換成數字型再比較,否則比較結果可能不是預期效果。
比如把本文中的order全部換成string型,輸出結果為
{"order":10,"name":"王五","age":"36"}{"order":5,"name":"李四","age":"22"}{"order":9,"name":"張三","age":"24"}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。