List集合实现自定义排序
2016-12-06 14:55
513 查看
List自定义排序根据Collections.sort重载方法来实现,实现Comparable接口。
实现Comparator
,重写compare方法。
student类:
实现Comparator
,重写compare方法。
public class DataSort implements Comparator<Student>{ /** * 重写方法 实现自定义排序 */ @Override public int compare(Student o1, Student o2) { int i = o1.getAge() - o2.getAge();//按照年龄排序(从小到大) //年龄相等的情况下 if(i == 0){ return 0; } return i; } public static void main(String[] args) { List<Student> students = new ArrayList<Student>(); students.add(new Student(11)); students.add(new Student(21)); students.add(new Student(31)); students.add(new Student(22)); students.add(new Student(15)); students.add(new Student(27)); for(Student stu : students) { System.out.println("age:" + stu.getAge()); } Collections.sort(students,new DataSort()); //排序 for(Student stu : students) { System.out.println("age:" + stu.getAge()); } } }
student类:
public class Student { private int age; public Student(int age) { super(); this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
相关文章推荐
- 使用Comparable、Comparator接口实现对对象数组、List集合自定义排序
- DataGridView 绑定List集合后实现自定义排序
- 在List范型集合中实现自定义条件复杂查询 .
- java中的list自定义排序以及倒排序的实现
- java Collections.sort()实现List排序的默认方法和自定义方法
- Java借助反射实现自定义对象List的排序
- 在List范型集合中实现自定义条件复杂查询
- C#实现List集合的自定义查询
- Android自定义Comparator,实现List按时间排序
- C#使用IComparer自定义List类实现排序的方法
- java Collections.sort()实现List排序的默认方法和自定义方法
- List集合排序(默认及自定义排序)
- List<T>泛型数组API自带的Sort() 排序方法根据自定义排序实现
- 对于集合中的自定义对象使用collections.sort 进行排序,需要实现compartor接口
- Android记录14--自定义Comparator,实现List按时间排序
- 在List范型集合中实现自定义条件复杂查询
- java学习笔记—自定义实现linkedList集合
- Java:集合,对列表(List)中的自定义对象按属性(字段)排序(正序、倒序)的方法
- Android记录14--自定义Comparator,实现List按时间排序
- java Collections.sort()实现List排序的默认方法和自定义方法