一、比如根据下面这个类的 age 字段进行排序:
public class Person {
private String name;
private int age;
}
排序可以根据 java.utils 下的 Collections 里有一个sort 方法排序,两种写法如下:
public class X {
public static void main(String[] args) {
List<Person> l = new ArrayList<>();
Person p1 = new Person();
Person p2 = new Person();
Person p3 = new Person();
l.add(p1); l.add(p2);l.add(p3);
p1.setAge(13);
p2.setAge(15);
p3.setAge(11);
// Collections.sort(l, new Comparator<Person>() {
// @Override
// public int compare(Person person1, Person person2) {
// return person1.getAge()-person2.getAge();
// }
// });
l.sort(new Comparator<Person>() {
@Override
public int compare(Person person1, Person person2) {
return person1.getAge()-person2.getAge();
}
});
for(Person list:l){
System.out.println(list.getAge());
}
}
}
输出结果:
11
13
15
Process finished with exit code 0
这里是从小到大排序,如果要从大到小排序可以更换 person1 和 person2 的位置就可以了:
l.sort(new Comparator<Person>() {
@Override
public int compare(Person person1, Person person2) {
return person2.getAge()-person1.getAge();
}
});
二、根据 String 的长度排序:
public class X {
public static void main(String[] args) {
List<Person> l = new ArrayList<>();
Person p1 = new Person();
Person p2 = new Person();
Person p3 = new Person();
l.add(p1); l.add(p2);l.add(p3);
p1.setName("zhangsan");
p2.setName("lisi");
p3.setName("wangermazi");
// Collections.sort(l, new Comparator<Person>() {
// @Override
// public int compare(Person person1, Person person2) {
// return person1.getAge()-person2.getAge();
// }
// });
l.sort(new Comparator<Person>() {
@Override
public int compare(Person person1, Person person2) {
return person2.getName().length()-person1.getName().length();
}
});
for(Person list:l){
System.out.println(list.getName());
}
}
}
输出结果:
wangermazi
zhangsan
lisi
Process finished with exit code 0