在Web开发中要排序都是基于sql的,不管事jdbc还是hibenrate、mybatis这些orm框架。。那么,如果单纯的拿到了一个结果集,我们在集合里怎么排序呢?
这里给出一个demo。。
首先看一个bean:
package com.test;
public class User {
private String userName;
private Integer age;
private Integer sex;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
}
package com.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
*
* @author xiatianlong
*
* @date 2016年8月10日 下午4:15:32
*/
public class CollectionSort {
public static void main(String[] args) {
List<User> userList = new ArrayList<User>();
// 初始化数据
for (int i = 0; i < 5; i++){
User user = new User();
if (i%2 == 0){
user.setUserName("张" + i + "开");
user.setSex(0);
}else{
user.setSex(1);
user.setUserName("李" + i + "山");
}
user.setAge(20 + i);
userList.add(user);
}
System.out.println("排序前:");
for (User user : userList) {
System.out.println(user.getUserName() + " " + user.getSex() + " " + user.getAge());
}
// 根据性别进行排序
Collections.sort(userList, new Comparator<User>() {
public int compare(User user1,User user2) {
return user1.getUserName().compareTo(user2.getUserName());
}
});
System.out.println("------------------");
System.out.println("根据性别排序后:");
for (User user : userList) {
System.out.println(user.getUserName() + " " + user.getSex() + " " + user.getAge());
}
}
}
看打印的结果: