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"}
原创文章,作者:3628473679,如若转载,请注明出处:https://blog.ytso.com/186030.html