欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java实现集合对象排序(单个字段)

程序员文章站 2022-06-14 22:42:04
...
好消息,百度网盘专业搜索网站上线了
打开瞧一瞧:http://bitar.cn
package com.collection;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SingleSort<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 = ((E)a).getClass().getMethod(method, new Class[]{});
					// 获取m2的方法名
					Method m2 = ((E)b).getClass().getMethod(method, new Class[]{});
					
					if (sort != null && "desc".equals(sort)) {

						ret = m2.invoke(((E)b), new Object[]{}).toString().compareTo(m1.invoke(((E)a),new Object[]{}).toString());

					} else {
						// 正序排序
						ret = m1.invoke(((E)a), new Object[]{}).toString().compareTo(m2.invoke(((E)b), new Object[]{}).toString());
					}
				} catch (Exception ne) {
					ne.printStackTrace();
				}
				return ret;
			}
		});
	}
	public static void main(String[] args) {
    	List<JavaBeanS> list = new ArrayList<JavaBeanS>();
    	JavaBeanS bean = new JavaBeanS(2,"张三","b");
    	list.add(bean);
    	bean = new JavaBeanS(1,"李四","d");
    	list.add(bean);
    	bean = new JavaBeanS(3,"王二","c");
    	list.add(bean);
    	bean = new JavaBeanS(4,"钱七","a");
    	list.add(bean);
    	
    	SingleSort<JavaBeanS> sorter = new SingleSort<JavaBeanS>();
    	sorter.Sort(list, "getAddress", "desc");
    	
        for (JavaBeanS obj : list) {
			System.out.println(obj.getId()+":"+obj.getName()+":"+obj.getAddress());
		}
	}
}
class JavaBeanS{
	private String name;
	private String address;
	private int id;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public JavaBeanS(int id,String name, String address) {
		super();
		this.name = name;
		this.address = address;
		this.id = id;
	}
}
相关标签: 集合排序 java