List自定义排序我习惯根据Collections.sort重载方法来实现,下面我只实现自己习惯方式。还有一种就是实现Comparable接口。
挺简单的,直接上代码吧。
package com.sort; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* list自定义排序
* @author root
*
*/
public class ListSort {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
User user1 = new User();
user1.setName("a");
user1.setAge(19);
user1.setOrder(10);
User user2 = new User();
user2.setName("b");
user2.setAge(20);
user2.setOrder(2);
User user3 = new User();
user3.setName("c");
user3.setAge(20);
user3.setOrder(1);
List<User> list = new ArrayList<User>();
list.add(user1);
list.add(user2);
list.add(user3);
/*自定义按照age排序
Collections.sort(list,new Comparator(){
@Override
public int compare(Object o1, Object o2) {
User u1 = (User)o1;
User u2 = (User)o2;
return u1.getAge().compareTo(u2.getAge());
}
});*/
//如果age相同,再按照order排序
Collections.sort(list,new Comparator(){
@Override
public int compare(Object o1, Object o2) {
User u1 = (User)o1;
User u2 = (User)o2;
int i = u1.getAge().compareTo(u2.getAge());
if(i == 0){
return u1.getOrder().compareTo(u2.getOrder());
}
return i;
}
});
for(User user : list){
System.out.println("Name:"+user.getName()+" Age:"+user.getAge()+" Order:"+user.getOrder());
}
}
}
User类:
package com.sort; public class User {
private String name;
private Integer age;
private Integer order;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getOrder() {
return order;
}
public void setOrder(Integer order) {
this.order = order;
} }