Java根据实体类的某一个属性进行排序
/**
* 用户实体类
*/
public class UserEntity {
private int id;
private String username;
private String sex;
private int age;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public UserEntity(int id, String username, String sex, int age, String address) {
this.id = id;
this.username = username;
this.sex = sex;
this.age = age;
this.address = address;
}
@Override
public String toString() {
return "UserEntity{" +
"id=" + id +
", username='" + username + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
public static void main(String[] args) {
UserEntity userEntity1 = new UserEntity(0, "张晓红","女",1 , "beijignshi");
UserEntity userEntity2 = new UserEntity(1, "李晓红","女",1 , "tianjinshi");
UserEntity userEntity3 = new UserEntity(3, "项羽","男",2 , "chuguo");
UserEntity userEntity4 = new UserEntity(4, "刘邦","男",2 , "hanchao");
List<UserEntity> list = new ArrayList<>();
list.add(userEntity2);
list.add(userEntity1);
list.add(userEntity4);
list.add(userEntity3);
System.out.println(Objects.toString(list));
}
输出结果:
[UserEntity{id=1, username='李晓红', sex='女', age=1, address='tianjinshi'},
UserEntity{id=0, username='张晓红', sex='女', age=1, address='beijignshi'},
UserEntity{id=4, username='刘邦', sex='男', age=2, address='chuguo'},
UserEntity{id=3, username='项羽', sex='男', age=2, address='hanchao'}]
public static List<UserEntity> sort(List<UserEntity> list){
//根据指定比较器产生的顺序对指定列表进行排序。
Collections.sort(list, new Comparator<UserEntity>() {
@Override
public int compare(UserEntity o1, UserEntity o2) {
//获取所需语言环境的 Collator,根据所需切换其他语言环境
//Collator collator = Collator.getInstance(Locale.ENGLISH);
//return collator.compare(o1.getAddress(), o2.getAddress());
Collator collator = Collator.getInstance(Locale.CANADA);
return collator.compare(o1.getUsername(), o2.getUsername());
}
});
return list;
}
输出结果:
[UserEntity{id=4, username='刘邦', sex='男', age=2, address='hanchao'},
UserEntity{id=0, username='张晓红', sex='女', age=1, address='beijignshi'},
UserEntity{id=1, username='李晓红', sex='女', age=1, address='tianjinshi'},
UserEntity{id=3, username='项羽', sex='男', age=2, address='chuguo'}]