重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
这篇文章给大家分享的是有关基于Java实现对象List排序的示例的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
成都创新互联公司-专业网站定制、快速模板网站建设、高性价比钟山网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式钟山网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖钟山地区。费用合理售后完善,十余年实体公司更值得信赖。
这篇文章主要介绍了如何基于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) { ListpoetList = new ArrayList (); 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 () { @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 () { @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}
感谢各位的阅读!关于“基于Java实现对象List排序的示例”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!