1.首先写一个简单的测试bean类
public class SortBean {
private String name;
private int age;
private int userId;
public SortBean(String name, int age, int userId) {
this.name = name;
this.age = age;
this.userId = userId;
}
public String getName() { return name; }
public void setName(String name) {this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public int getUserId() { return userId; }
public void setUserId(int userId) { this.userId = userId; }
}
2.写一个main类函数直接看效果
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortList {
public static void main(String[] args) {
List<SortBean> list = new ArrayList<>();
SortBean sortBean0 = new SortBean("德玛", 20, 20180001);
SortBean sortBean1 = new SortBean("寒冰", 18, 20180009);
SortBean sortBean2 = new SortBean("流浪", 99, 20180002);
list.add(sortBean0);
list.add(sortBean1);
list.add(sortBean2);
System.out.println("before sort ");
for (SortBean sortBean : list) {
System.out.println("name: " + sortBean.getName() + " age: " + sortBean.getAge());
}
Collections.sort(list, new Comparator<SortBean>() {
@Override
public int compare(SortBean o1, SortBean o2) {
if (o1.getAge() - o2.getAge() > 0) { //变成 < 可以变成递减排序
return 0;
} else {
return -1;
}
}
});
System.out.println("after sort ");
for (SortBean sortBean : list) {
System.out.println("name: " + sortBean.getName() + " age: " + sortBean.getAge());
}
}
}
3.输出效果
before sort
name: 德玛 age: 20
name: 寒冰 age: 18
name: 流浪 age: 99
after sort
name: 寒冰 age: 18
name: 德玛 age: 20
name: 流浪 age: 99
4.结语
其实建议在把内部匿名类变成 lambda 表达式(java 8 开始支持),代码会更加简洁
即:
把下面代码片
Collections.sort(list, new Comparator<SortBean>() {
@Override
public int compare(SortBean o1, SortBean o2) {
if (o1.getAge() - o2.getAge() > 0) {
return 0;
} else {
return -1;
}
}
});
替换成
list.sort((o1, o2) -> o1.getAge() - o2.getAge()); //递减排序的话改变减号的两个对象位置
这样的话程序就更加简洁