废话不多说,直接上代码。
UserVO.java
package com.lrb.sort.test; import java.io.Serializable; public class UserVO implements Serializable { private String userCde; private String userName; private int age; public UserVO(String userCde, String userName, int age) { super(); this.userCde = userCde; this.userName = userName; this.age = age; } public String getUserCde() { return userCde; } public void setUserCde(String userCde) { this.userCde = userCde; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
UserComparator.java
package com.lrb.sort.test; import java.util.Comparator; public class UserComparator implements Comparator { public int compare(Object o1, Object o2) { UserVO user1 = (UserVO) o1; UserVO user2 = (UserVO) o2; //首先比较用户编号,编号相同再比较名字,名字相同再比较年龄 int flag1 = user1.getUserCde().compareToIgnoreCase(user2.getUserCde()); if(flag1 == 0){ int flag2 = user1.getUserName().compareToIgnoreCase(user2.getUserName()); if(flag2 == 0){ return user1.getAge()<=user2.getAge()?-1:1; }else{ return flag2; } }else{ return flag1; } } }
package com.lrb.sort.test; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ListContainsBeanSort { public static void main(String[] args) { List testArry = new ArrayList(); //为要排序的集合添加测试数据 testArry.add(new UserVO("000012","工商银行天津分行",22)); testArry.add(new UserVO("000013","中国人发银行",23)); testArry.add(new UserVO("000015","招商银行济南分行",23)); testArry.add(new UserVO("00001801","招商银行高新区分行",23)); testArry.add(new UserVO("000045","民生银行总行",23)); testArry.add(new UserVO("00006709","民生银行济南分行",23)); testArry.add(new UserVO("000011","工商银行济南分行",23)); testArry.add(new UserVO("000012","工商银行天津分行",23)); testArry.add(new UserVO("000012","聊城工商银行分行",23)); //排序操作 Collections.sort(testArry, new UserComparator()); //展示排序后内容 for(int i=0;i<testArry.size();i++){ UserVO user = (UserVO) testArry.get(i); System.out.println(user.getUserCde()+"\t"+user.getUserName()+"\t"+user.getAge()); } } }
控制台打印排序后的结果:
000011 工商银行济南分行23
000012 工商银行天津分行22
000012 工商银行天津分行23
000012 聊城工商银行分行23
000013 中国人发银行 23
000015 招商银行济南分行23
00001801 招商银行高新区分行23
000045 民生银行总行 23
00006709 民生银行济南分行23