List<Object>排序
需求是根據(jù)一個對象的list中的某個字段的值排序,比如根據(jù)列表中人的年齡排序:
在實體類中繼承Comparable接口并重寫compareTo()方法,方法里是自己需求比較的函數(shù),可以根據(jù)自己的需求去寫钟些。
package com.example.Test;
/**
- @author Administrator
*/
public class TestObj implements Comparable<TestObj> {
public int id;
public String name;
public int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "TestObj [id=" + id + ", name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(TestObj o) {
// TODO Auto-generated method stub
return String.valueOf(this.getAge()).compareTo(String.valueOf(o.getAge()));
}
}
然后調(diào)用Collections.sort(list)進(jìn)行排序
@Test
public void testListSort() {
List<TestObj> list = new ArrayList<>();
TestObj obj1 = new TestObj();
obj1.setId(1);
obj1.setName("張三");
obj1.setAge(16);
TestObj obj2 = new TestObj();
obj2.setId(2);
obj2.setName("李四");
obj2.setAge(20);
TestObj obj3 = new TestObj();
obj3.setId(3);
obj3.setName("王五");
obj3.setAge(12);
TestObj obj4 = new TestObj();
obj4.setId(4);
obj4.setName("趙六");
obj4.setAge(24);
list.add(obj1);
list.add(obj2);
list.add(obj3);
list.add(obj4);
Collections.sort(list);
for (TestObj testObj : list) {
System.out.println(testObj.toString());
}
}
輸出結(jié)果
TestObj [id=3, name=王五, age=12]
TestObj [id=1, name=張三, age=16]
TestObj [id=2, name=李四, age=20]
TestObj [id=4, name=趙六, age=24]