JAVA里List集合中的对象根据对象的某个属性值降序或者升序排序

时间:2023-03-09 06:10:39
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; }
}