java中List对象排序的通用方法

对象实体:

/**
 * 学生实体类
 * @author chenchuang
 *
 */
public class Student {
	public Student(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	private int id;
	private String name;
	private int age;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}


工具类:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * List对象排序的通用方法
 * 
 * @author chenchuang
 * 
 * @param <E>
 */
public class ListSort<E> {
	/**
	 * 
	 * @param list 要排序的集合
	 * @param method 要排序的实体的属性所对应的get方法
	 * @param sort desc 为正序  
	 */
	public void Sort(List<E> list, final String method, final String sort) {
		// 用内部类实现排序
		Collections.sort(list, new Comparator<E>() {

			public int compare(E a, E b) {
				int ret = 0;
				try {
					// 获取m1的方法名
					Method m1 = a.getClass().getMethod(method, null);
					// 获取m2的方法名
					Method m2 = b.getClass().getMethod(method, null);
					
					if (sort != null && "desc".equals(sort)) {

						ret = m2.invoke(((E)b), null).toString().compareTo(m1.invoke(((E)a),null).toString());

					} else {
						// 正序排序
						ret = m1.invoke(((E)a), null).toString().compareTo(m2.invoke(((E)b), null).toString());
					}
				} catch (NoSuchMethodException ne) {
					System.out.println(ne);
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return ret;
			}
		});
	}
}


测试类:

import java.util.ArrayList;


public class ListTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ArrayList<Student> list= new ArrayList<Student>();
		list.add(new Student(1,"张三",5));
		list.add(new Student(2,"李四",4));
		list.add(new Student(3,"王五",3));
		list.add(new Student(4,"小明",2));
		list.add(new Student(5,"小黑",1));
		ListSort<Student> listSort= new ListSort<Student>();
		listSort.Sort(list, "getAge", "desc");
		for(Student s:list){
			System.out.println(s.getId()+s.getName()+s.getAge());
		}

	}

}


测试结果

1张三5
2李四4
3王五3
4小明2
5小黑1

以上就是Java 中List的排序通用方法,希望对大家有帮助

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值