简单集合排序
public static List<Integer> getIntegerList(){
List<Integer> integerList = new ArrayList<>();
integerList.add(23);
integerList.add(15);
integerList.add(35);
integerList.add(68);
integerList.add(43);
integerList.add(8);
return integerList;
}
@Test
public void sortIntegerList(){
List<Integer> integerList = getIntegerList();
System.out.println("排序前:"+integerList);
Collections.sort(integerList);
System.out.println("排序后:"+integerList);
}
输出:
排序前:[23, 15, 35, 68, 43, 8]
排序后:[8, 15, 23, 35, 43, 68]
根据对象集合某个字段排序
public static List<User> getUserList(){
List<User> userList = new ArrayList<>();
userList.add(new User("小明",11,"北京",66));
userList.add(new User("小红",12,"上海",99));
userList.add(new User("小詹",14,"广州",77));
userList.add(new User("小龙",16,"深圳",55));
userList.add(new User("小斯",9,"迈阿密",33));
userList.add(new User("小布",12,"伦敦",88));
return userList;
}
@Test
public void sortUserListByAge(){
List<User> userList = getUserList();
System.out.println("排序前:"+userList);
Collections.sort(userList, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
return o1.getAge() - o2.getAge();
}
});
System.out.println("排序后:"+userList);
}
输出:
排序前:[User(name=小明, age=11, city=北京, score=66), User(name=小红, age=12, city=上海, score=99),
User(name=小詹, age=14, city=广州, score=77), User(name=小龙, age=16, city=深圳, score=55),
User(name=小斯, age=9, city=迈阿密, score=33), User(name=小布, age=12, city=伦敦, score=88)]
排序后:[User(name=小斯, age=9, city=迈阿密, score=33), User(name=小明, age=11, city=北京, score=66),
User(name=小红, age=12, city=上海, score=99), User(name=小布, age=12, city=伦敦, score=88),
User(name=小詹, age=14, city=广州, score=77), User(name=小龙, age=16, city=深圳, score=55)]
根据对象集合多个字段排序
@Test
public void sortUserList(){
List<User> userList = getUserList();
System.out.println("排序前:"+userList);
Collections.sort(userList, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
int i = o1.getAge() - o2.getAge();
if(i == 0){
return o1.getScore() - o2.getScore();
}
return i;
}
});
System.out.println("排序后:"+userList);
}
输出:
排序前:[User(name=小明, age=11, city=北京, score=66), User(name=小红, age=12, city=上海, score=99),
User(name=小詹, age=14, city=广州, score=77), User(name=小龙, age=16, city=深圳, score=55),
User(name=小斯, age=9, city=迈阿密, score=33), User(name=小布, age=12, city=伦敦, score=88)]
排序后:[User(name=小斯, age=9, city=迈阿密, score=33), User(name=小明, age=11, city=北京, score=66),
User(name=小布, age=12, city=伦敦, score=88), User(name=小红, age=12, city=上海, score=99),
User(name=小詹, age=14, city=广州, score=77), User(name=小龙, age=16, city=深圳, score=55)]
|