[java]代码库
package com.dubbo.provider.main;
import com.dubbo.provider.bean.User;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import org.apache.log4j.Logger;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created by Administrator on 2017/3/25.
*/
public class OrderDemo {
private static Logger logger = Logger.getLogger(PinyinUtil.class.getName());
/**
* main方法,用于测试
*
* @param args
*/
public static void main(String[] args) {
//order1();
order2();
}
/**
* 对List<String>类型数据进行排序
*/
public static void order1() {
List<String> list = new ArrayList<String>();
list.add("易皇星");
list.add("阿弟");
list.add("冰球");
list.add("崇明");
list.add("邓小平");
list.add("sfsf");
list.add("jjrd");
//根据的汉字的拼音的字母排序
Collections.sort(list, Collator.getInstance(java.util.Locale.CHINA));
for (int i = 0; i < list.size(); i++) {
logger.info(list.get(i));
}
}
/**
* 对List<JavaBean>类型数据进行排序
*/
public static void order2() {
List<User> list = new ArrayList<User>();
list.add(new User(1, "易皇星", "1"));
list.add(new User(2, "阿弟", "2"));
list.add(new User(3, "冰球", "3"));
list.add(new User(4, "崇明", "4"));
list.add(new User(5, "邓小平", "5"));
list.add(new User(6, "sfsg", "6"));
list.add(new User(7, "fhf", "7"));
list.add(new User(8, "mdrgr", "8"));
list.add(new User(9, "24", "9"));
list.add(new User(10, "6", "10"));
list.add(new User(11, null, "11"));
//按照汉字拼音排序,支持汉字、英文混合排序。
PinyinComparator pinyinComparator = new PinyinComparator();
sort(list, "name", true, pinyinComparator);
logger.info(list);
}
/**
* 自定义排序方法
*
* @param list
* @param fieldName
* @param asc
* @param cmp
* @param <T>
*/
public static <T> void sort(List<T> list, String fieldName, boolean asc, Comparator<?> cmp) {
cmp = ComparatorUtils.nullLowComparator(cmp); // 允许null
if (!asc) {
cmp = ComparatorUtils.reversedComparator(cmp); // 逆序
}
Collections.sort(list, new BeanComparator(fieldName, cmp));
}
/**
* 自定义排序方法
*
* @param list
* @param fieldName
* @param asc
* @param <T>
*/
public static <T> void sort(List<T> list, String fieldName, boolean asc) {
Comparator<?> cmp = ComparableComparator.getInstance();
cmp = ComparatorUtils.nullLowComparator(cmp); // 允许null
if (!asc) {
cmp = ComparatorUtils.reversedComparator(cmp); // 逆序
}
Collections.sort(list, new BeanComparator(fieldName, cmp));
}
}
[源代码打包下载]
by: 发表于:2017-07-07 15:46:30 顶(0) | 踩(0) 回复
??
回复评论