Java8 按照對(duì)象屬性值排序或者多個(gè)屬性值排序

根據(jù)Person對(duì)象的年齡排序

/**
* 最炫寫法,將集合轉(zhuǎn)換成stream流處理,代碼量少 正序
集合+stream流+sort排序(實(shí)現(xiàn)比較器)+收集流處理完的數(shù)據(jù)
*/
personList.stream().sorted(Comparator.comparing(Person::getAge)).collect(Collectors.toList());

/**
*  倒序 reversed()
*/
 personList.stream().sorted(Comparator.comparing(Person::getAge).reversed()).collect(Collectors.toList());

/**
* 如果需要多條件排序,thenComparing(),對(duì)于排序完的結(jié)果還可以接著操作
*/
List<Person> collect = personList.stream().sorted(Comparator.comparing(Person::getAge).thenComparing(Comparator.comparing(Person::getName))).collect(Collectors.toList());


知其然,知其所以然.為什么這樣寫?

//java8 之前對(duì)于引用對(duì)象的比較需要實(shí)現(xiàn)自定義比較器,通常使用內(nèi)部類寫法實(shí)現(xiàn)
Collections.sort(personList, new Comparator<Person>() {
    @Override
    public int compare(Person o1, Person o2) {
          return o1.getAge().compareTo(o2.getAge());
        }
 });

在java8之后,可以將代碼改成這樣:

/**
*使用stream的sort()或者
 Collections的sort() 
 ----Lambda表達(dá)式
*/
Collections.sort(personList, (o1, o2) -> o1.getAge().compareTo(o2.getAge()));
personList.stream().sorted((o1, o2) -> o1.getAge().compareTo(o2.getAge()))

/**
*Lambda表達(dá)式+函數(shù)式接口+方法引用

如果我們想要調(diào)用的方法擁有一個(gè)名字,我們就可以通過(guò)它的名字直接調(diào)用它。 
Comparator byAge = Comparator.comparing(Person::getAge); 
方法引用的標(biāo)準(zhǔn)形式是:類名::方法名。(注意:只需要寫方法名,不需要寫括號(hào))
類型     示例
引用靜態(tài)方法     ContainingClass::staticMethodName
引用某個(gè)對(duì)象的實(shí)例方法     containingObject::instanceMethodName
引用某個(gè)類型的任意對(duì)象的實(shí)例方法     ContainingType::methodName
引用構(gòu)造方法     ClassName::new
靜態(tài)方法引用例子:
  String::valueOf   等價(jià)于lambda表達(dá)式 (s) -> String.valueOf(s);

  Math::pow   等價(jià)于lambda表達(dá)式  (x, y) -> Math.pow(x, y);    

*/

Collections.sort(personList, Comparator.comparing(Person::getAge));

基礎(chǔ)代碼:Person類


public class Person {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

//獲取集合數(shù)據(jù)
public static List<Person> getPerson(){
        List<Person> list = new ArrayList<>();
        int i = 1;
        do {
            Person p = new Person();
            p.setName("P" + i);
            p.setAge(i);
            list.add(p);
            i++;
        } while (i <= 10);
        return list;
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容