import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List; /**
* java工具类之按对象中某属性排序
* @author李坤 交流博客:http://blog.csdn.net/lk_blog
*/
public class SortListUtil { public static final String DESC = "desc";
public static final String ASC = "asc"; /**
* 对list中的元素按升序排列.
*
* @param list
* 排序集合
* @param field
* 排序字段
* @return
*/
public static List<?> sort(List<?> list, final String field) {
return sort(list, field, null);
} /**
* 对list中的元素进行排序.
*
* @param list
* 排序集合
* @param field
* 排序字段
* @param sort
* 排序方式: SortList.DESC(降序) SortList.ASC(升序).
* @return
*/
@SuppressWarnings("unchecked")
public static List<?> sort(List<?> list, final String field,
final String sort) {
Collections.sort(list, new Comparator() {
public int compare(Object a, Object b) {
int ret = 0;
try {
Field f = a.getClass().getDeclaredField(field);
f.setAccessible(true);
Class<?> type = f.getType(); if (type == int.class) {
ret = ((Integer) f.getInt(a)).compareTo((Integer) f
.getInt(b));
} else if (type == double.class) {
ret = ((Double) f.getDouble(a)).compareTo((Double) f
.getDouble(b));
} else if (type == long.class) {
ret = ((Long) f.getLong(a)).compareTo((Long) f
.getLong(b));
} else if (type == float.class) {
ret = ((Float) f.getFloat(a)).compareTo((Float) f
.getFloat(b));
} else if (type == Date.class) {
ret = ((Date) f.get(a)).compareTo((Date) f.get(b));
} else if (isImplementsOf(type, Comparable.class)) {
ret = ((Comparable) f.get(a)).compareTo((Comparable) f
.get(b));
} else {
ret = String.valueOf(f.get(a)).compareTo(
String.valueOf(f.get(b)));
} }catch (Exception e) {
e.printStackTrace();
}
if (sort != null && sort.toLowerCase().equals(DESC)) {
return -ret;
} else {
return ret;
} }
});
return list;
} /**
* 对list中的元素按fields和sorts进行排序,
* fields[i]指定排序字段,sorts[i]指定排序方式.如果sorts[i]为空则默认按升序排列.
*
* @param list
* @param fields
* @param sorts
* @return
*/
@SuppressWarnings("unchecked")
public static List<?> sort(List<?> list, String[] fields, String[] sorts) {
if (fields != null && fields.length > 0) {
for (int i = fields.length - 1; i >= 0; i--) {
final String field = fields[i];
String tmpSort = ASC;
if (sorts != null && sorts.length > i && sorts[i] != null) {
tmpSort = sorts[i];
}
final String sort = tmpSort;
Collections.sort(list, new Comparator() {
public int compare(Object a, Object b) {
int ret = 0;
try {
Field f = a.getClass().getDeclaredField(field);
f.setAccessible(true);
Class<?> type = f.getType();
if (type == int.class) {
ret = ((Integer) f.getInt(a))
.compareTo((Integer) f.getInt(b));
} else if (type == double.class) {
ret = ((Double) f.getDouble(a))
.compareTo((Double) f.getDouble(b));
} else if (type == long.class) {
ret = ((Long) f.getLong(a)).compareTo((Long) f
.getLong(b));
} else if (type == float.class) {
ret = ((Float) f.getFloat(a))
.compareTo((Float) f.getFloat(b));
} else if (type == Date.class) {
ret = ((Date) f.get(a)).compareTo((Date) f
.get(b));
} else if (isImplementsOf(type, Comparable.class)) {
ret = ((Comparable) f.get(a))
.compareTo((Comparable) f.get(b));
} else {
ret = String.valueOf(f.get(a)).compareTo(
String.valueOf(f.get(b)));
} } catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} if (sort != null && sort.toLowerCase().equals(DESC)) {
return -ret;
} else {
return ret;
}
}
});
}
}
return list;
} /**
* 默认按正序排列
*
* @param list
* @param method
* @return
*/
public static List<?> sortByMethod(List<?> list, final String method) {
return sortByMethod(list, method, null);
} @SuppressWarnings("unchecked")
public static List<?> sortByMethod(List<?> list, final String method,
final String sort) {
Collections.sort(list, new Comparator() {
public int compare(Object a, Object b) {
int ret = 0;
try {
Method m = a.getClass().getMethod(method, null);
m.setAccessible(true);
Class<?> type = m.getReturnType();
if (type == int.class) {
ret = ((Integer) m.invoke(a, null))
.compareTo((Integer) m.invoke(b, null));
} else if (type == double.class) {
ret = ((Double) m.invoke(a, null)).compareTo((Double) m
.invoke(b, null));
} else if (type == long.class) {
ret = ((Long) m.invoke(a, null)).compareTo((Long) m
.invoke(b, null));
} else if (type == float.class) {
ret = ((Float) m.invoke(a, null)).compareTo((Float) m
.invoke(b, null));
} else if (type == Date.class) {
ret = ((Date) m.invoke(a, null)).compareTo((Date) m
.invoke(b, null));
} else if (isImplementsOf(type, Comparable.class)) {
ret = ((Comparable) m.invoke(a, null))
.compareTo((Comparable) m.invoke(b, null));
} else {
ret = String.valueOf(m.invoke(a, null)).compareTo(
String.valueOf(m.invoke(b, null)));
} if (isImplementsOf(type, Comparable.class)) {
ret = ((Comparable) m.invoke(a, null))
.compareTo((Comparable) m.invoke(b, null));
} else {
ret = String.valueOf(m.invoke(a, null)).compareTo(
String.valueOf(m.invoke(b, null)));
} }catch (Exception it) {
System.out.println(it);
} if (sort != null && sort.toLowerCase().equals(DESC)) {
return -ret;
} else {
return ret;
}
}
});
return list;
} @SuppressWarnings("unchecked")
public static List<?> sortByMethod(List<?> list, final String methods[],
final String sorts[]) {
if (methods != null && methods.length > 0) {
for (int i = methods.length - 1; i >= 0; i--) {
final String method = methods[i];
String tmpSort = ASC;
if (sorts != null && sorts.length > i && sorts[i] != null) {
tmpSort = sorts[i];
}
final String sort = tmpSort;
Collections.sort(list, new Comparator() {
public int compare(Object a, Object b) {
int ret = 0;
try {
Method m = a.getClass().getMethod(method, null);
m.setAccessible(true);
Class<?> type = m.getReturnType();
if (type == int.class) {
ret = ((Integer) m.invoke(a, null))
.compareTo((Integer) m.invoke(b, null));
} else if (type == double.class) {
ret = ((Double) m.invoke(a, null))
.compareTo((Double) m.invoke(b, null));
} else if (type == long.class) {
ret = ((Long) m.invoke(a, null))
.compareTo((Long) m.invoke(b, null));
} else if (type == float.class) {
ret = ((Float) m.invoke(a, null))
.compareTo((Float) m.invoke(b, null));
} else if (type == Date.class) {
ret = ((Date) m.invoke(a, null))
.compareTo((Date) m.invoke(b, null));
} else if (isImplementsOf(type, Comparable.class)) {
ret = ((Comparable) m.invoke(a, null))
.compareTo((Comparable) m.invoke(b,
null));
} else {
ret = String.valueOf(m.invoke(a, null))
.compareTo(
String.valueOf(m
.invoke(b, null)));
} } catch (NoSuchMethodException ne) {
System.out.println(ne);
} catch (IllegalAccessException ie) {
System.out.println(ie);
} catch (InvocationTargetException it) {
System.out.println(it);
} if (sort != null && sort.toLowerCase().equals(DESC)) {
return -ret;
} else {
return ret;
}
}
});
}
}
return list;
} /**
* 判断对象实现的所有接口中是否包含szInterface
*
* @param clazz
* @param szInterface
* @return
*/
public static boolean isImplementsOf(Class<?> clazz, Class<?> szInterface) {
boolean flag = false; Class<?>[] face = clazz.getInterfaces();
for (Class<?> c : face) {
if (c == szInterface) {
flag = true;
} else {
flag = isImplementsOf(c, szInterface);
}
} if (!flag && null != clazz.getSuperclass()) {
return isImplementsOf(clazz.getSuperclass(), szInterface);
} return flag;
} public static void main(String[] args) throws Exception {
List<Student> list = new ArrayList<Student>(); list.add(new Student(3, "b", 1, new Date(11110000)));
list.add(new Student(1, "c", 3, new Date(44440000)));
list.add(new Student(2, "a", 2, new Date(22210000)));
list.add(new Student(4, "a", 11, new Date(33330000)));
System.out.println("-------原来序列-------------------");
for (Student stu : list) {
System.out.println(stu.toString());
} // 按age正序排序,注意结果排完后是1,2,3,11. 不是1,11,2,3(如果是String类型正序排序是这样)
SortListUtil.sort(list, "age", null);
System.out.println("---------测试Integer和正序,按age正序排序-----------------");
for (Student stu : list) {
System.out.println(stu.toString());
} // 按id倒序
SortListUtil.sort(list, "id", SortListUtil.DESC);
System.out.println("--------测试int和倒序,按id倒序------------------");
for (Student stu : list) {
System.out.println(stu.toString());
} // 先按name正序排序,再按id正序排序
SortListUtil.sort(list, new String[] { "name", "id" }, new String[] {});
System.out
.println("---------测试多个排序字段,先按name正序,name相同时再按id正序-----------------");
for (Student stu : list) {
System.out.println(stu.toString());
} // 先按name正序排序,再按id倒序排序
SortListUtil.sort(list, new String[] { "name", "id" }, new String[] {
SortListUtil.ASC, SortListUtil.DESC });
System.out
.println("---------测试多个排序字段,先按name正序,name相同时再按id倒序-----------------");
for (Student stu : list) {
System.out.println(stu.toString());
} // 按birthday排序
SortListUtil.sort(list, "birthday");
System.out
.println("---------测试实现了Comparable接口的对象排序,按birthday正序-----------------");
for (Student stu : list) {
System.out.println(stu.toString());
} // sortByMethod
SortListUtil.sortByMethod(list, "getId", null);
System.out.println("---------测试sortByMethod,按getId方法正序-----------------");
for (Student stu : list) {
System.out.println(stu.toString());
} }
}

  

java工具类之按对象中某属性排序的更多相关文章

  1. Java工具类 通过ResultSet对象返回对应的实体List集合

    自从学了JDBC用多了像一下这种代码: List<xxx> list = new Array<xxx>(); if(rs.next()){ xxx x = new xxx(); ...

  2. java工具类去掉字符串String中的.点。android开发java程序员常用工具类

    下面是工具类详细代码: package com.qq986945193.david; /** * qq986945193 Project * ============================= ...

  3. js 对象数组根据对象中的属性排序

    function createComparisonFunction(propertyName){ return function(object1,object2){ var value1 = obje ...

  4. 使用这些高效Java工具类享受开发乐趣

    使用这些高效Java工具类享受开发乐趣导语在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.在开发中,使用这些工具类,不仅可以提高编码效率,还可以提高 ...

  5. Java中使用最频繁及最通用的Java工具类

    在Java中,工具类定义了一组公共方法,Java中使用最频繁及最通用的Java工具类. 一. org.apache.commons.io.IOUtils closeQuietly:关闭一个IO流.so ...

  6. Java并发工具类CountDownLatch源码中的例子

    Java并发工具类CountDownLatch源码中的例子 实例一 原文描述 /** * <p><b>Sample usage:</b> Here is a pai ...

  7. Java工具类——通过配置XML验证Map

    Java工具类--通过配置XML验证Map 背景 在JavaWeb项目中,接收前端过来的参数时通常是使用我们的实体类进行接收的.但是呢,我们不能去决定已经搭建好的框架是怎么样的,在我接触的框架中有一种 ...

  8. 排名前 16 的 Java 工具类

    在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...

  9. 排名前16的Java工具类

    原文:https://www.jianshu.com/p/9e937d178203 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法 ...

随机推荐

  1. Java容器-引入Guava类库

    目录 1.只读设置 2.函数式编程+组合式编程 3.约束条件 4.集合操作(并集.差集.交集) 代码实现 1.只读设置 public static void main(String [] args){ ...

  2. CentOS 6.9永久设置静态路由表以及路由表常用设置

    一.路由表常用设置: 1.使用route命令添加的路由,机器重启或者网卡重启后路由就失效了,方法: //添加到主机的路由 # route add –host 192.168.1.11 dev eth0 ...

  3. shell 快速移动,快捷操作

    ctr+h 往后删除一字符 ctr+d 往前删除一字符 ctr+b 光标往前 ctr+f 往后ctr+u 删除到最前 ctr+K删除到最后ctr+a 光标到最前 ctr+e 光标到最后ctr+p 往上 ...

  4. JS之RegExp对象(一)

    JavaScript提供了一个RegExp对象来完毕有关正則表達式的操作和功能,每一条正則表達式模式相应一个RegExp实例.有两种方式能够创建RegExp对象的实例.      使用RegExp的显 ...

  5. 禁止body滚动允许div滚动防微信露底

    最近遇到一个需求,页面中只有一个div允许滚动,其他内容不允许滚动. 正常来讲加上 body{height:100%;overflow: hidden;} 应该就阻止页面滚动了.可是很悲催的是手机端并 ...

  6. tomcat JVM内存 配置

    原文:http://elf8848.iteye.com/blog/467460 常见的内存溢出有以下两种: java.lang.OutOfMemoryError: PermGen space java ...

  7. sqlserver锁机制详解(sqlserver查看锁)

    简介 在SQL Server中,每一个查询都会找到最短路径实现自己的目标.如果数据库只接受一个连接一次只执行一个查询.那么查询当然是要多快好省的完成工作.但对于 大多数数据库来说是需要同时处理多个查询 ...

  8. 描述 Machine.Config 和 Web.Config(转载)

    NET Framework 提供的配置管理包括范围广泛的设置,允许管理员管理 Web 应用程序及其环境.这些设置存储在 XML 配置文件中,其中一些控制计算机范围的设置,另一些控制应用程序特定的配置. ...

  9. [Android 新特性] 改进明显 Android 4.4系统新特性解析

    Android 4.3发布半年之后,Android 4.4随着新一代Nexus5一起出现在了用户的面前,命名为从之前的Jelly Bean(果冻豆)换成了KitKat(奇巧).这个新系统究竟都有怎样的 ...

  10. 【转载】秒杀场景下MySQL的低效原因和改进以及Redis的处理

    分享的PPT在如下网址: http://www.doc88.com/p-4199037770087.html 秒杀场景下mysql的低效原因和改进 另外有一个篇文章是针对以上内容的总结: http:/ ...