集合类List存放的数据,默认是按照放入时的顺序存放的,比如依次放入A、B、C,则取得时候,则也是A、B、C的顺序,实际场景中,有时我们需要根据自定义的规则对List中的元素进行排序,该如何实现呢?
看下面小例子:
package test.tool.gui.dbtool.util; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Test { public static void main(String[] args) { Listlist = new ArrayList (); //创建3个学生对象,年龄分别是20、19、21,并将他们依次放入List中 Student s1 = new Student(); s1.setAge(20); Student s2 = new Student(); s2.setAge(19); Student s3 = new Student(); s3.setAge(21); list.add(s1); list.add(s2); list.add(s3); System.out.println("排序前:"+list); Collections.sort(list, new Comparator (){ /* * int compare(Student o1, Student o2) 返回一个基本类型的整型, * 返回负数表示:o1 小于o2, * 返回0 表示:o1和o2相等, * 返回正数表示:o1大于o2。 */ 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("排序后:"+list); } } class Student{ private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return getAge()+""; } }
执行结果:
排序前:[20, 19, 21]排序后:[19, 20, 21]
标签:
List集合中的对象根据属性排序