Java 實現 對象List 進行排序


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}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM