Java List集合排序实现方法解析
这篇文章主要介绍了JavaList集合排序实现方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
1.使用Collections工具类中的sort()方法
参数不同:
voidsort(Listlist)在自定义类User里面实现Comparable
voidsort(Listlist,Comparatorc)第二个参数为了省事,可以直接使用匿名内部类
publicclassUserimplementsComparable{ privateintscore; privateintage; publicUser(intscore,intage){ super(); this.score=score; this.age=age; } publicintgetScore(){ returnscore; } publicvoidsetScore(intscore){ this.score=score; } publicintgetAge(){ returnage; } publicvoidsetAge(intage){ this.age=age; } @Override publicintcompareTo(Usero){ inti=this.getAge()-o.getAge();//先按照年龄排序 if(i==0){ returnthis.score-o.getScore();//如果年龄相等了再用分数进行排序 } returni; } } publicstaticvoidmain(String[]args){ List users=newArrayList (); users.add(newUser(78,26)); users.add(newUser(67,23)); users.add(newUser(34,56)); users.add(newUser(55,23)); Collections.sort(users); for(Useruser:users){ System.out.println(user.getScore()+","+user.getAge()); } } 
publicclassStudents{
privateintage;
privateintscore;
publicStudents(intage,intscore){
super();
this.age=age;
this.score=score;
}
publicintgetAge(){
returnage;
}
publicvoidsetAge(intage){
this.age=age;
}
publicintgetScore(){
returnscore;
}
publicvoidsetScore(intscore){
this.score=score;
}
}
publicstaticvoidmain(String[]args){
Liststudents=newArrayList();
students.add(newStudents(23,100));
students.add(newStudents(27,98));
students.add(newStudents(29,99));
students.add(newStudents(29,98));
students.add(newStudents(22,89));
Collections.sort(students,newComparator(){
@Override
publicintcompare(Studentso1,Studentso2){
inti=o1.getScore()-o2.getScore();
if(i==0){
returno1.getAge()-o2.getAge();
}
returni;
}
});
for(Studentsstu:students){
System.out.println("score:"+stu.getScore()+":age"+stu.getAge());
}
}   
2.直接使用list.sort()方法,传入实现Comparator接口的实现类的实例,为了省事直接传入匿名内部类
publicclassStudents{
privateintage;
privateintscore;
publicStudents(intage,intscore){
this.age=age;
this.score=score;
}
publicintgetAge(){
returnage;
}
publicvoidsetAge(intage){
this.age=age;
}
publicintgetScore(){
returnscore;
}
publicvoidsetScore(intscore){
this.score=score;
}
}
publicstaticvoidmain(String[]args){
Liststudents=newArrayList();
students.add(newStudents(23,100));
students.add(newStudents(27,98));
students.add(newStudents(29,99));
students.add(newStudents(29,98));
students.add(newStudents(22,89));
students.sort(newComparator(){
@Override
publicintcompare(Studentso1,Studentso2){
inti=o1.getScore()-o2.getScore();
if(i==0){
returno1.getAge()-o2.getAge();
}
returni;
}
});
for(Studentsstu:students){
System.out.println("score:"+stu.getScore()+":age"+stu.getAge());
}
}   
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。