java的排序类 Collections


场景:比如说有一个List<Student> 里面有许多学生 我们想让这些学生按照年龄的大小排序

 

我们可以用java自带的 java.util.Collections 工具类来实现  

Collections.sort(rootList, studentComparator); public Comparator<Student> studentComparator = new Comparator<Student>() { public int compare(Student o1, Student o2) { return o1.getAge() - o2.getAge(); //从小到大 } };

解释一下:sort方法  第一个是需要排序的list    第二个是排序的规则    规则是自己自定义的   

 

多个字段排序,比如先排年龄,年龄相同再排姓名  

 
Collections.sort(rootList, studentComparator); public Comparator<Student> studentComparator = new Comparator<Student>() { public int compare(Student o1, Student o2) { int age=o1.getAge() - o2.getAge(); if(age==0){ return o1.getName() - o2.getName(); }else{ return age; } } };

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM