集合内部先实现按年龄排序再实现以姓名排序
定义一个实体存放需要排序的数据
package ListAscByCollectionsMethod; /* * 定义一个实体,存放数据。 */ public class User { String name; String age; public User(String name,String age){ this.name=name; this.age=age; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
实现comparator接口,定义排序规则:
package ListAscByCollectionsMethod; import java.util.Comparator; /* * 定义一个排序规则 */ public class ComparatorUser implements Comparator{ @Override public int compare(Object arg0, Object arg1) { User user0=(User)arg0; User user1=(User)arg1; //首先比较年龄,如果年龄相同,则比较名字 int flag=user0.getAge().compareTo(user1.getAge()); if(flag==0){ return user0.getName().compareTo(user1.getName()); }else{ return flag; } } }
测试定义的排序规则:
package ListAscByCollectionsMethod; import java.util.ArrayList; import java.util.Collections; import java.util.List; 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")); for (int i=0;i<userlist.size();i++){ User user_temp=(User)userlist.get(i); System.out.print(user_temp.getAge()+"/"+user_temp.getName()+"\t"); } System.out.println(); 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()); } } }
运行:
无排序结果:
4/dd 1/aa 5/ee 2/bb 5/ff 3/cc 6/gg
有排序结果:
1,aa 2,bb 3,cc 4,dd 5,ee 5,ff 6,gg