JAVA⾥List集合中的对象根据对象的某个属性值降序或者升序
排序
java集合排序怎么实现需要使⽤JDK1.8及以上
package com.stream;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<TestDto> Dtos();
//根据TestDto对象的priority字段降序排序
dtoList.sort(Comparatorparing(TestDto::getPriority).reversed());
/
/根据TestDto对象的sort字段升序排序
// dtoList.sort(Comparatorparing(TestDto::getSort));
for (TestDto d:dtoList
) {
System.out.println(d);
}
}
}
//多个字段排序
//先以属性⼀降序,再进⾏属性⼆降序多个字段后⾯追加即可
list.stream().sorted(Comparatorparing(类::属性⼀,verseOrder()).thenComparing(类::属性⼆,verseOrder()));
⾃定义⽅法排序
List<TestDto> list=getDtos();
Collections.sort(list, (TestDto b1, TestDto b2) -> {
/**
* 可以⾃定义⽅法,
* 返回 1 ->排在上⾯
* 返回 -1 ->排在下⾯
*/
if (b1.getPriority()&Priority()){
return -1;
}
return 1;
});
TestDto.java
package com.stream;
st.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;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。