对象按照某属性升序,降序
只是写了按照对象里面的id排序,如果按照其余的字段升降序也可以实现。
/** * 个人信息排序 * @author wWX154783 * */public class PersonSort{ public static void main(String[] args) { List<Person> list = new ArrayList<Person>(); for (int i = 0; i < 10; i++) { Person person = new Person(); person.setId(new Random().nextInt(50)); list.add(person); } System.out.println("原始:\t" + list); Collections.sort(list, new PersonOrderByIdAsc()); System.out.println("升序:\t" + list); Collections.sort(list, new PersonOrderByIdDesc()); System.out.println("降序:\t" + list); }}/* 人 */class Person implements Comparator<Person>{ private int id; private int age; private String name; private String sex; private String address; public int compare(Person o1, Person o2) { return 0; } 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; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "id=" + this.id; }}/* 按照person id升序 */class PersonOrderByIdAsc extends Person{ @Override public int compare(Person o1, Person o2) { if (o1.getId() > o2.getId()) { return 1; } else if (o1.getId() < o2.getId()) { return -1; } else { return 0; } }}/* 按照person id降序 */class PersonOrderByIdDesc extends Person{ @Override public int compare(Person o1, Person o2) { if (o1.getId() < o2.getId()) { return 1; } else if (o1.getId() > o2.getId()) { return -1; } else { return 0; } }}