怎样基于Java实现对象List排序
人气:0这篇文章主要介绍了如何基于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针对ArrayList自定义排序的2种实现方法
- java list集合排序按某一属性排序操作
- JAVA像SQL一样对List对象集合进行排序
- Java8 用Lambda表达式给List集合排序的实现
- Java实现对两个List快速去重并排序操作示例
- Java中对list map根据map某个key值进行排序的方法
- java根据List内对象的属性排序方法
- java中List对象列表实现去重或取出及排序的方法
- Java Collections.sort()实现List排序的默认方法和自定义方法
- java 中List按照date排序的实现
- Java对List进行排序的两种实现方法
- Java如何实现List自定义排序
加载全部内容