這篇文章給大家分享的是有關(guān)基于Java實(shí)現(xiàn)對(duì)象List排序的示例的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
成都創(chuàng)新互聯(lián)公司-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價(jià)比鐘山網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式鐘山網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋鐘山地區(qū)。費(fèi)用合理售后完善,十余年實(shí)體公司更值得信賴。
這篇文章主要介紹了如何基于Java實(shí)現(xiàn)對(duì)象List排序,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
按照對(duì)象中的某個(gè)屬性,對(duì)對(duì)象List進(jìn)行排序。
以初唐四杰的成績排名為例,對(duì)詩人進(jìn)行排序。
Java實(shí)現(xiàn)如下:
1、詩人(Poet)類結(jié)構(gòu),定義如下:
/** * 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())); // 按照分?jǐn)?shù)排名(從高到低) 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==> 按照分?jǐn)?shù)排名(從高到低)如下:"); poetList.forEach(poet -> System.out.println(poet.toString())); // 按照分?jǐn)?shù)排名(從低到高) 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==> 按照分?jǐn)?shù)排名(從低到高)如下:"); poetList.forEach(poet -> System.out.println(poet.toString())); }}
3、運(yùn)行結(jié)果如下:
==> 初始順序如下:Poet{name='楊炯', score=94.0}Poet{name='盧照鄰', score=92.5}Poet{name='駱賓王', score=95.0}Poet{name='王勃', score=99.5}==> 按照分?jǐn)?shù)排名(從高到低)如下:Poet{name='王勃', score=99.5}Poet{name='駱賓王', score=95.0}Poet{name='楊炯', score=94.0}Poet{name='盧照鄰', score=92.5}==> 按照分?jǐn)?shù)排名(從低到高)如下:Poet{name='盧照鄰', score=92.5}Poet{name='楊炯', score=94.0}Poet{name='駱賓王', score=95.0}Poet{name='王勃', score=99.5}
感謝各位的閱讀!關(guān)于“基于Java實(shí)現(xiàn)對(duì)象List排序的示例”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!