1. Collections.sort()排序
1.list集合里面存放对象person,比如要根据person对象的年龄进行排序:
利用Collections.sort()方法,重写里面的comparator方法,相当于内部类:
public class SortTest {
public static void main(String[] args) {
String s = "aaa";
String string = new String("aaa");
System.out.println("----=-----"+string==s);
List<Student> list = new ArrayList<>();
Student a = new Student("张三", 18);
Student b = new Student("李四",20);
Student c = new Student("王五",22);
Student d = new Student("招六",21);
list.add(a);
list.add(b);
list.add(c);
list.add(d);
System.out.println("排序前的结果:"+list);
System.out.println(System.currentTimeMillis());
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if(o1.getAge() > o2.getAge()) {
return -1;
}
if(o1.getAge() == o2.getAge()) {
return 0;
}
return 1;
}
});
System.out.println(System.currentTimeMillis());
System.out.println("排序后的:"+list);
//如果是普通类型
List<Integer> alist = new ArrayList<>();
alist.add(1);
alist.add(2);
alist.add(5);
alist.add(3);
alist.add(4);
System.out.println(alist);
Collections.sort(alist);//升序排列
System.out.println(alist);
Collections.reverse(alist);
System.out.println(alist);//降序排列
Collections.shuffle(alist);//打乱
System.out.println(alist);
}
}
- 让pojo对象实现comparable接口,并且重写里面的compareTo方法:
//想根据年龄排序 需要实现comparable接口 并重写compareTo方法
public class Person implements Comparable<Person>{
private String name;
private int age;
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Person p) {
if(this.age < p.getAge()) {
return 1;
}else if(this.age == p.getAge()) {
return 0;
}
return -1;
}
@Override
public boolean equals(Object obj) {
if(this == obj) {
return true;
}
if(!(obj instanceof Student)) {
return false;
}
Student s = (Student)obj;
return this.name==s.name&&this.age==s.age;
}
}