ArrayList排序:Comparator
// 按照id排序-->从小到大排序:userId1 > userId2 return 1;
// userId1 < userId2 return -1; userId1 = userId2 return 0;
private void ascendingOrder(List<User> userList) {
Comparator<User> comparator1 = new Comparator<User>() {
@Override
public int compare(User lhs, User rhs) {
int userId1 = lhs.userId;
int userId2 = rhs.userId;
if (userId1 > userId2) {
return 1;
} else if (userId1 < userId2) {
return -1;
} else {
return 0;
}
}
};
Collections.sort(userList, comparator1);
StringBuilder builder = new StringBuilder();
for (User user : userList) {
builder.append(user.userId).append(user.userName).append(user.hobby).append("\n");
}
textView1.setText(builder.toString());
}
// 按照id排序-->从大到小排序:userId1 > userId2 return -1;
// userId1 < userId2 return 1; userId1 = userId2 return 0;
private void descendingOrder(List<User> userList) {
Comparator<User> comparator2 = new Comparator<User>() {
@Override
public int compare(User lhs, User rhs) {
int userId1 = lhs.userId;
int userId2 = rhs.userId;
if (userId1 > userId2) {
return -1;
} else if (userId1 < userId2) {
return 1;
} else {
return 0;
}
}
};
Collections.sort(userList, comparator2);
StringBuilder builder = new StringBuilder();
for (User user : userList) {
builder.append(user.userId).append(user.userName).append(user.hobby).append("\n");
}
textView2.setText(builder.toString());
}
效果图: