如何基于Java实现对象List排序
这篇文章主要介绍了如何基于Java实现对象List排序,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
按照对象中的某个属性,对对象List进行排序。
以初唐四杰的成绩排名为例,对诗人进行排序。
Java实现如下:
1、诗人(Poet)类结构,定义如下:
/** *CreatedbyMiracleLunaon2020/1/11 */ publicclassPoet{ privateStringname; privateDoublescore; publicPoet(Stringname,Doublescore){ this.name=name; this.score=score; } publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicDoublegetScore(){ returnscore; } publicvoidsetScore(Doublescore){ this.score=score; } @Override publicStringtoString(){ return"Poet{"+ "name='"+name+'\''+ ",score="+score+ '}'; } }
2、诗人按照成绩排名,代码如下:
importjava.util.ArrayList; importjava.util.Comparator; importjava.util.List; /** *CreatedbyMiracleLunaon2020/1/11 */ publicclassPoetSort{ publicstaticvoidmain(String[]args){ ListpoetList=newArrayList (); Poetpoet1=newPoet("杨炯",94.0); poetList.add(poet1); Poetpoet2=newPoet("卢照邻",92.5); poetList.add(poet2); Poetpoet3=newPoet("骆宾王",95.0); poetList.add(poet3); Poetpoet4=newPoet("王勃",99.5); poetList.add(poet4); //初始顺序 System.out.println("==>初始顺序如下:"); poetList.forEach(poet->System.out.println(poet.toString())); //按照分数排名(从高到低) poetList.sort(newComparator (){ @Override publicintcompare(Poetpoet1,Poetpoet2){ Doublescore1=poet1.getScore(); Doublescore2=poet2.getScore(); returnscore2.compareTo(score1); } }); System.out.println("\n==>按照分数排名(从高到低)如下:"); poetList.forEach(poet->System.out.println(poet.toString())); //按照分数排名(从低到高) poetList.sort(newComparator (){ @Override publicintcompare(Poetpoet1,Poetpoet2){ Doublescore1=poet1.getScore(); Doublescore2=poet2.getScore(); returnscore1.compareTo(score2); } }); System.out.println("\n==>按照分数排名(从低到高)如下:"); poetList.forEach(poet->System.out.println(poet.toString())); } }
3、运行结果如下:
==>初始顺序如下: Poet{name='杨炯',score=94.0} Poet{name='卢照邻',score=92.5} Poet{name='骆宾王',score=95.0} Poet{name='王勃',score=99.5} ==>按照分数排名(从高到低)如下: Poet{name='王勃',score=99.5} Poet{name='骆宾王',score=95.0} Poet{name='杨炯',score=94.0} Poet{name='卢照邻',score=92.5} ==>按照分数排名(从低到高)如下: Poet{name='卢照邻',score=92.5} Poet{name='杨炯',score=94.0} Poet{name='骆宾王',score=95.0} Poet{name='王勃',score=99.5}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。