java 根据对象属性排序
在项目中经常会遇到这杨的情况,在数据中取到的 一个list集合我们需要这个集合是按我们想要的顺序排列
当然你说这可以用数据库order by 就能搞定,ok我们说的用java代码。若你已经选择要使用数据库了请绕行!
好吧居然你选择了往下继续OK 就进入代码吧,
ok之前我遇到这样的需求的时候为了简单也使用过数据库来做,后来数据库查询的sql越来越复杂之后就想用j
ava来帮帮数据库减轻一下压力。"毕竟,压力来自轮胎,就算跳到250P,FC 的马力还是太大,难以做到最大限度的飘逸"。
我靠这好像是“头文字D”的台词吧!不管了!
之前我也想自己实现一个,我去真的有点蛋疼,(首先遇到的问题就是,居然要根据对象的属性排序,那么对象是不确定的
,属性也是不能确定的,这必然就会用到反射,而且如果要按照对象都的字符串属性排序那么?????是不是有点隐隐的疼(-~-) );
最后还是妥协了百度了一下,恰巧好看到这哥们的文章...
http://blog.csdn.net/djun100/article/details/11873281
package com.test;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.commons.collections.comparators.ComparatorChain;
public class MapSort {
public class Person implements Comparable<Person> {
private String name;
private Integer age;
public Person(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Person o) {
// TODO Auto-generated method stub
return 0;
}
}
public static void main(String[] args) {
//
// String[] names = new String[] { "张三丰", "张无忌","张无忌", "张无忌","张无忌", "张无忌","张无忌", "张信哲", "张张张", "周润发", "马云", "牛强东", "马化腾", "齐向东", "赵云", "马超", "什么",
// "知乎", "www.baidu.com", "火狐", "微软", "杭州", "2015春节" };
String[] names = new String[] { "张三丰", "张无忌","张无忌", "张无忌","张无忌", "张无忌","张无忌", "张信哲", "张张张" };
List<Person> perList = new ArrayList<Person>();
Comparator mycmp = ComparableComparator.getInstance();
mycmp = ComparatorUtils.nullLowComparator(mycmp); // 允许null
// mycmp = ComparatorUtils.reversedComparator(mycmp); // 逆序
Comparator<Object> comparator = Collator.getInstance(java.util.Locale.CHINA);
ArrayList<Object> sortFields = new ArrayList<Object>();
sortFields.add(new BeanComparator("name", comparator)); // name正序 (主)
sortFields.add(new BeanComparator("age", mycmp)); // id逆序 (副)
ComparatorChain multiSort = new ComparatorChain(sortFields);
System.out.println("======排序前=====");
System.out.println(perList);
Collections.sort(perList, multiSort);
System.out.println("======排序hou=====");
System.out.println( perList );
// resMap.put("2", perListTwo);
// resMap.put("three", perListThree);
// resMap.put("4", perListFour);
}
}