JAVA Collections.sort()排序的一个用法。
假设有以下实体类User。现在我们对rank进行排序
public class User{
private String name;
private Integer rank;
public User(String name, Integer rank) {
this.name = name;
this.rank = rank;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getRank() {
return rank;
}
public void setRank(Integer rank) {
this.rank = rank;
}
}
以下是排序的测试类
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class test{
public static void main(String[] args) {
System.out.println("---start---");
List<User> user = new ArrayList<User>();
user.add(new User("lufy", 25));
user.add(new User("robin", 105));
user.add(new User("sanji", 25));
user.add(new User("zoro", 98));
user.add(new User("nami", 14));
Collections.sort(user,new Comparator<User>(){
public int compare(User arg0, User arg1) {
return arg0.getRank().compareTo(arg1.getRank());
}
});
for (User user2 : user) {
System.out.println(user2.getName()+"\t名次:"+user2.getRank());
}
System.out.println("---end---");
}
}
输出结果为:
---start---
nami 名次:14
lufy 名次:25
sanji 名次:25
zoro 名次:98
robin 名次:105
---end---