因为常常用到java集合list的排序,总结了下以下集中方法:
1.简单集合排序
List<String> li = new ArrayList<>();
li.add("1");
li.add("2");
//正序
Collections.sort(li);
//反序
Collections.reverse(li);
2.集合里面是对象的自定义排序
class User {
String userName;
Integer sort;
User(String userName, Integer sort) {
this.userName = userName;
this.sort = sort;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
}
List<User> userLi = new ArrayList<>();
userLi.add(new User("张三", 1));
userLi.add(new User("李四", 2));
//正序
Collections.sort(userLi, Comparator.comparing(User::getSort));
//反序(用自定义排序)
Collections.sort(userLi, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
return o2.getSort().compareTo(o1.getSort());
}
});