自定义对象中文排序,可以指定排序的字段名,较为通用

来源:互联网 发布:wp 添加js 编辑:程序博客网 时间:2024/06/05 06:24
public final class Sorting {    public static void main(String[] args) {        List<Person> persons = new ArrayList<>();        persons.add(new Person(2, "张三","北京"));        persons.add(new Person(1, "李四","aaa"));        persons.add(new Person(3, "王五","广州"));        persons.add(new Person(4, "赵六","深圳"));        Collections.sort(persons, new SortedUtil("name"));        for (Person person : persons) {            System.out.println(person.getId() + "" + person.getName());        }        Collections.sort(persons, new SortedUtil("address"));        for (Person person : persons) {            System.out.println(person.getId() + "" + person.getName() + " " + person.getAddress());        }    }}/** * 根据传入的字段进行中文排序 */class SortedUtil implements Comparator<Object> {    private Collator collator = Collator.getInstance(Locale.CHINA);    private String field;    public SortedUtil(String field) {        this.field = field;    }    @Override    public int compare(Object o1, Object o2) {        String name = this.field;        String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);        try {            Method method = o1.getClass().getMethod(methodName);            try {                Object invoke1 = method.invoke(o1);                Object invoke2 = method.invoke(o2);                return collator.compare(invoke1, invoke2);            } catch (IllegalAccessException e) {                e.printStackTrace();            } catch (InvocationTargetException e) {                e.printStackTrace();            }        } catch (NoSuchMethodException e) {            e.printStackTrace();        }        return 0;    }}class Person {    private int id;    private String name;    private String address;    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }    public Person(int id, String name, String address) {        this.id = id;        this.name = name;        this.address = address;    }    public Person(int id, String name) {        this.id = id;        this.name = name;    }    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;    }}


最简单的实现,未做优化。



0 0