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.stream().sorted(Comparator.comparing(类::属性一).thenComparing(类::属性二));

 

记得后面要使用.collect(Collectors.toList()),stream流只有使用了才会执行,不然只是像上面这样写的话 是不会生效的

 

自定义方法排序

 List<TestDto> list=getDtos();

        Collections.sort(list, (TestDto b1, TestDto b2) -> {
            /**
             * 可以自定义方法,用(前一个)b1和(后一个)b2比较
             * b1大于b2 =>返回 1 ->  b1在b2前面
             * b1大于b2 =>返回 -1 -> b2在b1前面
             */
            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;


    }
}

 

posted @ 2020-11-05 14:27  yvioo  阅读(7855)  评论(0编辑  收藏  举报