1、stream()的排序示例:
@Data
@ApiModel("测试实体类")
public class TestVo implements Serializable {
private static final long serialVersionUID = 1L;
@JsonFormat(shape = JsonFormat.Shape.STRING)
@ApiModelProperty(value = "自增ID")
private Long id;
private BigDecimal step;
private BigDecimal amount;
}
List<TestVo> testList = new ArrayList<>();
TestVo s1 = new TestVo();
s1.setStep(BigDecimal.valueOf(100));
s1.setAmount(BigDecimal.valueOf(10));
TestVo s2 = new TestVo();
s2.setStep(BigDecimal.valueOf(300));
s2.setAmount(BigDecimal.valueOf(40));
TestVo s3 = new TestVo();
s3.setStep(BigDecimal.valueOf(200));
s3.setAmount(BigDecimal.valueOf(40));
testList.add(s1);
testList.add(s2);
testList.add(s3);
//第1种:按照对象中step字段进行排序(从小到大)
testList = testList.stream().sorted(Comparator.comparing(TestVo::getStep))
.collect(Collectors.toList());
//第2种:按照对象中step字段进行排序(从大到小),加reversed()函数
testList =
testList.stream().sorted(Comparator.comparing(TestVo::getStep).reversed())
.collect(Collectors.toList());
//第3种:按照对象中step字段进行排序(从大到小),用compareTo()方法进行大小比较
testList = testList .stream().sorted((ss1, ss2) -> {
if (ss1.getStep().compareTo(ss2.getStep()) > 0) {
return -1;
} else {
return 1;
}
}).collect(Collectors.toList());
//第4种:按照对象中amout字段进行分组,可用于校验重复字段
//根据amout字段进行分组,将amout作为key
Map<BigDecimal, List<TestVo>> resultMap =
ruleInfoList.stream().collect(Collectors.groupingBy(TestVo::getAmount));
for(Map.Entry<BigDecimal, List<TestVo>> entry: resultMap.entrySet()){
//循环遍历,当entry的value.size()>1时,表示amout字段有重复的
if(entry.getValue().size() > 1){
System.out.println("amout字段有重复的");
for(TestVoinfo info: entry.getValue()){
//处理逻辑
......
}
}
}
2、compareTo()用法示例:
返回0:两个值相等;
返回-1:前值小于后值;
返回1:前值大于后值
public static void main(String[] args) {
BigDecimal s1 = new BigDecimal("1.5");
BigDecimal s2 = new BigDecimal("1.50");
BigDecimal s3 = new BigDecimal("2.5");
int result1 = s1.compareTo(s2); // 返回0,因为两个值相等
int result2 = s1.compareTo(s3); // 返回-1,因为s1小于s3
int result3 = s3.compareTo(s1); // 返回1,因为s3大于s1
System.out.println("s1.compareTo(s2): " + result1);
System.out.println("s1.compareTo(s3): " + result2);
System.out.println("s3.compareTo(s1): " + result3);
}
返参示例: