实体类list排序
工具类EntityListSort
/**
* @program: YeeGuideServer
* @description: list对象排序
* @author: jiahao
* @create: 2019-08-06 17:05
**/
public class EntityListSort {
/**
* @param list : list对象
* @param variable : 排序字段
* @description 返回负数表示:variable1 小于 variable2,
* 返回0 表示:variable1 等于 variable2,
* 返回正数表示:variable1 大于 variable2,
* @author jia hao
* @Date 2019/8/6 19:02
*/
public static <T> void sort(List<T> list, String variable) {
GenericsUtils genericsUtils = new GenericsUtils();
Collections.sort(list, (vo1, vo2) -> {
final Integer variable1 = Integer.valueOf(genericsUtils.getVariable(vo1, variable));
final Integer variable2 = Integer.valueOf(genericsUtils.getVariable(vo2, variable));
if (variable1 > variable2) {
return 1;
}
if (variable1.equals(variable2)) {
return 0;
}
return -1;
});
}
}
这里涉及到另外一个工具类, 泛型反射工具类
//泛型反射,获取变量值
final Integer variable1 = Integer.valueOf(genericsUtils.getVariable(vo1, variable));
final Integer variable2 = Integer.valueOf(genericsUtils.getVariable(vo2, variable));
实体类ExcelTraceVO
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
public class ExcelTraceVO {
/**
* 经度
*/
private Double lon;
/**
* 纬度
*/
private Double lat;
/**
* 排序
*/
private Integer sort;
}
测试类
public static void main(String[] args) {
List<ExcelTraceVO> voList = new ArrayList<>();
for (int i = 1; i < 10; i++) {
DecimalFormat df = new DecimalFormat( "0.0000" );
final ExcelTraceVO build = ExcelTraceVO.builder()
.lon(Double.valueOf(df.format(Math.random()*100)))
.lat(Double.valueOf(df.format(Math.random()*100)))
.sort((int) (Math.random() * 10 + 1))
.build();
voList.add(build);
}
System.out.println(voList);
EntityListSort.sort(voList, "sort");
System.out.println(voList);
}
结果
未执行排序方法前
执行排序方法后