对list集合排序,排序字段不确定

实体类

package com.spang.wechat.controller.report.analysis.model;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.math.BigDecimal;

/**
 * @author: meng.huan
 * @create: 2023-08-29 09:02
 * @description:
 */
@Data
@ApiModel(value = "TradeVolumeRatioVo", description = "集团侧数据看板-公司交易量占比")
public class TradeVolumeRatioVo implements Serializable {
    @ApiModelProperty("排名")
    private Integer rank;

    @ApiModelProperty("公司名称")
    private String companyName;

    @ApiModelProperty("交易量")
    private BigDecimal tradeVolume;

    @ApiModelProperty("计划产量")
    private BigDecimal productionPlan;

    @ApiModelProperty("交易量占比")
    private BigDecimal tradeVolumeRatio;

    public static Comparable getField(TradeVolumeRatioVo obj, String field) {
        switch (field) {
            case "tradeVolume":
                return obj.getTradeVolume();
            case "productionPlan":
                return obj.getProductionPlan();
            case "tradeVolumeRatio":
                return obj.getTradeVolumeRatio();
            default:
                throw new IllegalArgumentException("无效的字段名: " + field);
        }
    }

}
        //排序
        List<TradeVolumeRatioVo> result;
        //排序
        if(StringUtils.isBlank(fields)){
            //默认按照交易量
            Comparator<Object> comparator = Comparator.comparing(o -> (BigDecimal) TradeVolumeRatioVo.getField((TradeVolumeRatioVo) o,"tradeVolumeRatio"),Comparator.nullsFirst(BigDecimal::compareTo)).thenComparing(o -> (BigDecimal) TradeVolumeRatioVo.getField((TradeVolumeRatioVo) o,"tradeVolume"),Comparator.nullsFirst(BigDecimal::compareTo));
            result = resultList.stream().sorted(comparator.reversed()).collect(Collectors.toList());
        }else{
            Comparator<TradeVolumeRatioVo> comparator = Comparator.comparing(o -> (BigDecimal) TradeVolumeRatioVo.getField(o,fields),Comparator.nullsFirst(BigDecimal::compareTo));
            if(Objects.equals(sort, "descending")){
                result = resultList.stream().sorted(comparator.reversed()).collect(Collectors.toList());
            }else{
                result = resultList.stream().sorted(comparator).collect(Collectors.toList());
            }

        }

空值处理

        ModelMapper modelMapper = new ModelMapper();
        modelMapper.addConverter(new BigDecimalConverter());
        List<TradeVolumeRatioVoo> results = result.stream().map(source -> modelMapper.map(source,TradeVolumeRatioVoo.class)).collect(Collectors.toList());
    @Override
    public String convert(MappingContext<BigDecimal, String> mappingContext) {
        BigDecimal sourceValue = mappingContext.getSource();
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        nf.setRoundingMode(RoundingMode.HALF_UP);
        return sourceValue != null ? nf.format(sourceValue) : "-";
    }

你可能感兴趣的:(实战经验,list,数据结构)