collections.sort对javabean的list
1、collection.sort排序
为安仁等地区用户提供了全套网页设计制作服务,及安仁网站建设行业解决方案。主营业务为成都网站制作、网站建设、外贸网站建设、安仁网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!
算法底层实际是 将集合转换成array,再执行arrays.sort,arrays.sort利用归并排序,优化的快排,timSort等方式。
2、对string类型数据排序
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类型数据排序
(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实现了comparable接口,而自定义的javabean未实现,可以用这种方式排序
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实现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型数字,需要转换成数字型再比较,否则比较结果可能不是预期效果。
比如把本文中的order全部换成string型,输出结果为
{"order":10,"name":"王五","age":"36"}{"order":5,"name":"李四","age":"22"}{"order":9,"name":"张三","age":"24"}
新闻标题:collections.sort对javabean的list
文章位置:http://myzitong.com/article/gppphp.html