Java排序之集合排序
2016-10-12 本文已影响22人
亮之于东
集合排序
- 要么让集合的对象具有比较性也就是让集合中的对象实现Comparable<T>接口
- 自定义比较器实现Comparator<T>
举例:按人的年龄排序
代码如下
- UserBean对象
/**
* Created by yuandl on 2016-10-10.
*/
public class UserBean implements Comparable<UserBean> {
private String name;
private int age;
public UserBean(String name, int age) {
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 "UserBean{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(UserBean o) {
return this.age-o.age;
}
}
- 主要代码
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created by yuandl on 2016-10-10.
*/
public class ListTest {
public static void main(String args[]) {
List<UserBean> list = new ArrayList<>();
list.add(new UserBean("张三", 56));
list.add(new UserBean("张2", 5));
list.add(new UserBean("张6", 34));
list.add(new UserBean("张5", 6));
list.add(new UserBean("张9", 76));
Collections.sort(list);//让list中的对象具有比较性即UserBean implements Comparable<UserBean>
Collections.sort(list, new Comparator<UserBean>() {//自定义比较器
@Override
public int compare(UserBean o1, UserBean o2) {
return o1.getAge()-o2.getAge();
}
});
System.out.println(list);
}
}