lambda表达式thenComparing使用示例
需求:要实现对 List 导出结果按工号从小到大排序,每个工号的足迹内容按照时间顺序倒序,同一个时间不同生效序号倒序展示
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
// JobFootprintVO 类定义
@Data
public class JobFootprintVO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "员工工号")
private String emplid;
@ApiModelProperty(value = "时间")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private LocalDate effdt;
@ApiModelProperty(value = "序号")
private Integer effseq;
}
public class Main {
public static void main(String[] args) {
// 模拟数据
List<JobFootprintVO> jobFootprintVOs = new ArrayList<>();
JobFootprintVO vo1 = new JobFootprintVO();
vo1.setEmplid("002");
vo1.setEffdt(LocalDate.of(2025, 2, 18));
vo1.setEffseq(1);
jobFootprintVOs.add(vo1);
JobFootprintVO vo2 = new JobFootprintVO();
vo2.setEmplid("001");
vo2.setEffdt(LocalDate.of(2025, 2, 17));
vo2.setEffseq(2);
jobFootprintVOs.add(vo2);
JobFootprintVO vo3 = new JobFootprintVO();
vo3.setEmplid("001");
vo3.setEffdt(LocalDate.of(2025, 2, 17));
vo3.setEffseq(1);
jobFootprintVOs.add(vo3);
// 排序操作
List<JobFootprintVO> sortedList = sortJobFootprintVOs(jobFootprintVOs);
// 输出排序后的结果
for (JobFootprintVO vo : sortedList) {
System.out.println("工号: " + vo.getEmplid() + ", 时间: " + vo.getEffdt() + ", 序号: " + vo.getEffseq());
}
}
public static List<JobFootprintVO> sortJobFootprintVOs(List<JobFootprintVO> jobFootprintVOs) {
return jobFootprintVOs.stream()
.sorted(Comparator.comparing(JobFootprintVO::getEmplid)
.thenComparing(JobFootprintVO::getEffdt, Comparator.reverseOrder())
.thenComparing(JobFootprintVO::getEffseq, Comparator.reverseOrder()))
.toList();
}
}