JAVA里List集合中的對象根據對象的某個屬性值降序或者升序排序


 

需要使用JDK1.8及以上

 

package com.stream;


import java.util.Comparator;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<TestDto> dtoList=TestDto.getDtos();

        //根據TestDto對象的priority字段降序排序 
        dtoList.sort(Comparator.comparing(TestDto::getPriority).reversed());
        //根據TestDto對象的sort字段升序排序
       // dtoList.sort(Comparator.comparing(TestDto::getSort));


        for (TestDto d:dtoList
             ) {
            System.out.println(d);
        }
    }
}

 

//多個字段排序
//先以屬性一降序,再進行屬性二降序 多個字段 后面追加即可
list.stream().sorted(Comparator.comparing(類::屬性一,Comparator.reverseOrder()).thenComparing(類::屬性二,Comparator.reverseOrder()));

 

 

自定義方法排序

 List<TestDto> list=getDtos();

        Collections.sort(list, (TestDto b1, TestDto b2) -> { /** * 可以自定義方法, * 返回 1 ->排在上面 * 返回 -1 ->排在下面 */ if (b1.getPriority()>b2.getPriority()){ return -1; } return 1; });

 

 

 

TestDto.java

package com.stream;

import com.test.Test;

import java.util.ArrayList;
import java.util.List;

public class TestDto {

    private Integer id;

    private Integer sort;

    private Integer priority;

    public TestDto(Integer id, Integer sort, Integer priority) {
        this.id = id;
        this.sort = sort;
        this.priority = priority;
    }

    public TestDto() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getSort() {
        return sort;
    }

    public void setSort(Integer sort) {
        this.sort = sort;
    }

    public Integer getPriority() {
        return priority;
    }

    public void setPriority(Integer priority) {
        this.priority = priority;
    }

    @Override
    public String toString() {
        return "TestDto{" +
                "id=" + id +
                ", sort=" + sort +
                ", priority=" + priority +
                '}';
    }

    public static List<TestDto> getDtos(){
        List<TestDto> dtos=new ArrayList<>();

        TestDto dto1=new TestDto(1,2,3);

        TestDto dto2=new TestDto(2,3,1);

        TestDto dto3=new TestDto(3,1,2);

        dtos.add(dto1);
        dtos.add(dto2);

        dtos.add(dto3);

        return dtos;


    }
}

 


免責聲明!

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



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