如何基于Java实现对象List排序
程序员文章站
2022-05-30 13:13:50
这篇文章主要介绍了如何基于java实现对象list排序,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
按照对象中的某个属性,对对象...
这篇文章主要介绍了如何基于java实现对象list排序,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
按照对象中的某个属性,对对象list进行排序。
以初唐四杰的成绩排名为例,对诗人进行排序。
java实现如下:
1、诗人(poet)类结构,定义如下:
/** * created by miracle luna on 2020/1/11 */ public class poet { private string name; private double score; public poet(string name, double score) { this.name = name; this.score = score; } public string getname() { return name; } public void setname(string name) { this.name = name; } public double getscore() { return score; } public void setscore(double score) { this.score = score; } @override public string tostring() { return "poet{" + "name='" + name + '\'' + ", score=" + score + '}'; } }
2、诗人按照成绩排名,代码如下:
import java.util.arraylist; import java.util.comparator; import java.util.list; /** * created by miracle luna on 2020/1/11 */ public class poetsort { public static void main(string[] args) { list<poet> poetlist = new arraylist<poet>(); poet poet1 = new poet("杨炯", 94.0); poetlist.add(poet1); poet poet2 = new poet("卢照邻", 92.5); poetlist.add(poet2); poet poet3 = new poet("骆宾王", 95.0); poetlist.add(poet3); poet poet4 = new poet("王勃", 99.5); poetlist.add(poet4); // 初始顺序 system.out.println("==> 初始顺序如下:"); poetlist.foreach(poet -> system.out.println(poet.tostring())); // 按照分数排名(从高到低) poetlist.sort(new comparator<poet>() { @override public int compare(poet poet1, poet poet2) { double score1 = poet1.getscore(); double score2 = poet2.getscore(); return score2.compareto(score1); } }); system.out.println("\n==> 按照分数排名(从高到低)如下:"); poetlist.foreach(poet -> system.out.println(poet.tostring())); // 按照分数排名(从低到高) poetlist.sort(new comparator<poet>() { @override public int compare(poet poet1, poet poet2) { double score1 = poet1.getscore(); double score2 = poet2.getscore(); return score1.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}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: 学习OpenMV
下一篇: Python第三章 异常处理