package javaTest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ListSort<E> {
public static void main(String[] args) {
List<User> list = new ArrayList<User>();
// 创建3个学生对象,年龄分别是20、19、21,并将他们依次放入List中
User u1 = new User();
u1.setAge(20);
u1.setBirthDay("1998-01-01");
User u2 = new User();
u2.setAge(19);
u2.setBirthDay("1999-01-01");
User u3 = new User();
u3.setAge(21);
u3.setBirthDay("1997-01-01");
list.add(u1);
list.add(u2);
list.add(u3);
System.out.println("排序前:" + list);
//把人员按照年龄从小到大排列
Collections.sort(list, new Comparator<User>() {
@Override
public int compare(User u1, User u2) {
if (u1.getAge() > u2.getAge()) {
return 1;
}
if (u1.getAge() == u2.getAge()) {
return 0;
}
return -1;
}
});
System.out.println("升序排序后:" + list);
//把人员按照年龄从大到排列
Collections.sort(list, new Comparator<User>() {
public int compare(User u1, User u2) {
// 按照学生的年龄进行降序排列
if (u1.getAge() > u2.getAge()) {
return -1;
}
if (u1.getAge() == u2.getAge()) {
return 0;
}
return 1;
}
});
System.out.println("降序排序后:" + list);
//把人员按照出生日期从小到大排列
Collections.sort(list, new Comparator<User>() {
public int compare(User u1, User u2) {
return u1.getBirthDay().compareTo(u2.getBirthDay()); //大于返回1;小于返回-1;等于返回0
}
});
System.out.println("降序排序后:" + list);
//把人员按照出生日期从大到小排列
Collections.sort(list, new Comparator<User>() {
public int compare(User u1, User u2) {
return -u1.getBirthDay().compareTo(u2.getBirthDay()); //大于返回1;小于返回-1;等于返回0
}
});
System.out.println("降序排序后:" + list);
//如果字段为boolean型,可以采用下面的方式比较大小
Boolean b1 = true; // 创建Boolean对象1
Boolean b2 = false; // 创建Boolean对象0
Boolean b3 = true; // 创建Boolean对象1
System.out.println(b1);
int i;
i = b1.compareTo(b2); // b1和b2进行比较 i=1
System.out.println(i);//1-0
i = b2.compareTo(b1); // b2和b1进行比较 i=-1
System.out.println(i);//0-1
i = b1.compareTo(b3); // b1和b3进行比较 i=0
System.out.println(i);//1-1
}
}
class User{
private int age;
private String birthDay;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getBirthDay() {
return birthDay;
}
public void setBirthDay(String birthDay) {
this.birthDay = birthDay;
}
@Override
public String toString() {
return getAge()+":"+getBirthDay();
}
}
根据list中对象的某个属性值对list进行排序
最新推荐文章于 2022-08-17 11:15:56 发布