如何基于Java實現(xiàn)對象List排序
更新時間:2020年01月14日 10:29:02 作者:龍凌云端
這篇文章主要介紹了如何基于Java實現(xiàn)對象List排序,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
這篇文章主要介紹了如何基于Java實現(xiàn)對象List排序,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
按照對象中的某個屬性,對對象List進行排序。
以初唐四杰的成績排名為例,對詩人進行排序。
Java實現(xiàn)如下:
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()));
// 按照分數(shù)排名(從高到低)
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==> 按照分數(shù)排名(從高到低)如下:");
poetList.forEach(poet -> System.out.println(poet.toString()));
// 按照分數(shù)排名(從低到高)
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==> 按照分數(shù)排名(從低到高)如下:");
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}
==> 按照分數(shù)排名(從高到低)如下:
Poet{name='王勃', score=99.5}
Poet{name='駱賓王', score=95.0}
Poet{name='楊炯', score=94.0}
Poet{name='盧照鄰', score=92.5}
==> 按照分數(shù)排名(從低到高)如下:
Poet{name='盧照鄰', score=92.5}
Poet{name='楊炯', score=94.0}
Poet{name='駱賓王', score=95.0}
Poet{name='王勃', score=99.5}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
springboot發(fā)布dubbo服務注冊到nacos實現(xiàn)方式
這篇文章主要介紹了springboot發(fā)布dubbo服務注冊到nacos實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09
使用google.kaptcha來生成圖片驗證碼的實現(xiàn)方法
這篇文章主要介紹了使用google.kaptcha來生成圖片驗證碼的實現(xiàn)方法,非常不錯具有一定的參考借鑒價值,需要的朋友可以參考下2018-09-09
Spring?Security實現(xiàn)基于RBAC的權限表達式動態(tài)訪問控制的操作方法
這篇文章主要介紹了Spring?Security實現(xiàn)基于RBAC的權限表達式動態(tài)訪問控制,資源權限表達式動態(tài)權限控制在Spring Security也是可以實現(xiàn)的,首先開啟方法級別的注解安全控制,本文結合實例代碼給大家介紹的非常詳細,需要的朋友可以參考下2022-04-04

