您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關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}
感謝各位的閱讀!關于“Java實現對象List排序的案例”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。