背景:
现在有一个 User 对象,具有 name 和 age 属性。如果现在将多个 User 对象实例放入 List<User> 容器中,然后让你根据 User.name or User.age 排序,该如何做呢?
思路:
通过实现 Comparator 接口做一个 User 对象的比较器,然后传入容器对象和比较器利用 Collections.sort() API 进行排序。
User Class:
class User { String name; String age; public User(String name,String age){ this.name=name; this.age=age; } // Setter and Getter Methods
...... }
ComparatorUser Class:
public class ComparatorUser implements Comparator{ public int compare(Object obj0, Object obj1) { User user0=(User)obj0; User user1=(User)obj1; //首先比较年龄,如果年龄相同,则比较名字
int flag=user0.getAge().compareTo(user1.getAge()); if(flag==0){ return user0.getName().compareTo(user1.getName()); }else{ return flag; } } }
SortTest Class:
public class SortTest { public static void main(String[] args){ List userlist=new ArrayList(); userlist.add(new User("dd","4")); userlist.add(new User("aa","1")); userlist.add(new User("ee","5")); userlist.add(new User("bb","2")); userlist.add(new User("ff","5")); userlist.add(new User("cc","3")); userlist.add(new User("gg","6")); ComparatorUser comparator=new ComparatorUser(); Collections.sort(userlist, comparator); for (int i=0;i<userlist.size();i++){ User user_temp=(User)userlist.get(i); System.out.println(user_temp.getAge()+","+user_temp.getName()); } } }
测试结果:
1, aa
2, bb
3, cc
4, dd
5, ee
5, ff
6, gg
参考:
http://www.blogjava.net/zygcs/archive/2008/01/17/176032.html