模型属性处理

1. 复制非 null 属性

public static void copyNonNullProperties(Object source, Object target) {
    if (source == null || target == null) {
        return;
    }

    Class> sourceClass = source.getClass();
    Class> targetClass = target.getClass();
    List targetFieldNameList = Arrays.stream(targetClass.getDeclaredFields()).map(Field::getName).collect(Collectors.toList());

    try {
        for (Field sourceField : sourceClass.getDeclaredFields()) {
            sourceField.setAccessible(true);

            if (!targetFieldNameList.contains(sourceField.getName())) {
                continue;
            }
            Field targetField = targetClass.getDeclaredField(sourceField.getName());
            targetField.setAccessible(true);
            // static or final 类型字段不赋值 (比如 serialVersionUID)
            if (Modifier.isStatic(targetField.getModifiers()) || Modifier.isFinal(targetField.getModifiers())) {
                continue;
            }

            Object value = sourceField.get(source);
            if (value != null) {
                targetField.set(target, value);
            }
        }
    } catch (Exception e) {
        log.error(e.toString());
    }
}

2. 获取属性值

输出结果:

[{"pictureFalse":"1","pictureTrue":"1","type":"level2Type1","typeDesc":"二级type1"},
{"pictureFalse":"2","pictureTrue":"2","type":"level2Type2","typeDesc":"二级type2"},
{"pictureFalse":"0","pictureTrue":"0","type":"level2Type3","typeDesc":"二级type3"}]
@Test
public void copyField() {
    String text = "[n" +
            "    {n" +
            "        "code": "1",n" +
            "        "level2Type1": 1,n" +
            "        "level2Type2": 2,n" +
            "        "level2Type3": 3n" +
            "    },n" +
            "    {n" +
            "        "code": "0",n" +
            "        "level2Type1": 1,n" +
            "        "level2Type2": 2,n" +
            "        "level2Type3": 3n" +
            "    }n" +
            "]";

    List dataList = JSON.parseArray(text, TypeDTO.class);

    List qualityList = new ArrayList();
    List complaintTypeEnums = TypeEnum.getByParentCode("0");
    for (TypeEnum typeEnum : complaintTypeEnums) {
        QualityDTO qualityDTO = new QualityDTO();
        qualityDTO.setType(typeEnum.getCode());
        qualityDTO.setTypeDesc(typeEnum.getDesc());
        qualityDTO.setPictureTrue(String.valueOf(typeSum(dataList, typeEnum.getCode(), typeDTO -> DEFAULT_ZERO.equals(typeDTO.getCode()))));
        qualityDTO.setPictureFalse(String.valueOf(typeSum(dataList, typeEnum.getCode(), typeDTO -> DEFAULT_ONE.equals(typeDTO.getCode()))));
        qualityList.add(qualityDTO);
    }

    System.out.println(JSON.toJSONString(qualityList));
}
public static final String DEFAULT_ZERO = "0";
public static final String DEFAULT_ONE = "1";

private Long typeSum(List dataList, String fieldName, Predicate condition) {
    return dataList.stream()
            .filter(condition)
            .mapToLong(typeDTO -> Long.parseLong(getFieldValue(typeDTO, fieldName)))
            .sum();
}

private String getFieldValue(Object object, String fieldName) {
    try {
        Class> clazz = object.getClass();
        Field field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);
        Object obj = field.get(object);
        return obj == null ? DEFAULT_ZERO : obj.toString();
    } catch (Exception e) {
        log.error(e.toString());
        return DEFAULT_ZERO;
    }
}

2.2 模型

public enum TypeEnum {

    LEVEL2_TYPE1("0", "level2Type1", "二级type1"),
    LEVEL2_TYPE2("0", "level2Type2", "二级type2"),
    LEVEL2_TYPE3("0", "level2Type3", "二级type3"),
    LEVEL3_TYPE10("level2Type1", "level3Type10", "三级type10"),
    LEVEL3_TYPE11("level2Type1", "level3Type11", "三级type11"),
    LEVEL3_TYPE20("level2Type2", "level3Type20", "三级type20"),
    ;

    private String parentCode;
    private String code;
    private String desc;

    TypeEnum(String parentCode, String code, String desc) {
        this.parentCode = parentCode;
        this.code = code;
        this.desc = desc;
    }

    public String getParentCode() {
        return parentCode;
    }

    public String getCode() {
        return code;
    }

    public String getDesc() {
        return desc;
    }

    public static List getByParentCode(String parentCode) {
        if (StringUtils.isEmpty(parentCode)) {
            return new ArrayList();
        }
        List list = new ArrayList();
        for (TypeEnum value : TypeEnum.values()) {
            if (value.getParentCode().equals(parentCode)) {
                list.add(value);
            }
        }
        return list;
    }
}
@Data
public class TypeDTO {

    private String code;

    /**
     * 二级类型
     */
    private Long level2Type1;
    private Long level2Type2;

    /**
     * 三级类型
     */
    private Long level3Type10;
    private Long level3Type11;
    private Long level3Type20;
}

@Data
public class QualityDTO {
    private String type;
    private String typeDesc;

    /**
     * 回传图片为真
     */
    private String pictureTrue;
    /**
     * 回传图片为假
     */
    private String pictureFalse;

}

3. 默认项补位处理

输出结果:

[{"code":"home","label":"上门","percentRate":"33.33%","rate":0.3333,"total":1},
{"code":"self","label":"自提","percentRate":"66.67%","rate":0.6667,"total":2},
{"code":"wait","label":"待定","percentRate":"0.00%","rate":0.0,"total":0}]
@Test
public void def() {
    Map defLabelMap = new HashMap();
    defLabelMap.put("home", "上门");
    defLabelMap.put("self", "自提");
    defLabelMap.put("wait", "待定");

    String text = "[n" +
            "    {n" +
            "        "code": "home",n" +
            "        "total": 1n" +
            "    },n" +
            "    {n" +
            "        "code": "self",n" +
            "        "total": 2n" +
            "    }n" +
            "]";
    List dataList = JSON.parseArray(text, ItemDTO.class);

    calculateItemRate(dataList, defLabelMap);
    System.out.println(JSON.toJSONString(dataList));
}

public void calculateItemRate(List itemList, Map itemLabelMap) {
    if (CollectionUtils.isEmpty(itemList)) {
        return;
    }

    Long sum = itemList.stream()
            .filter(item -> item.getTotal() != null)
            .mapToLong(ItemDTO::getTotal)
            .sum();

    for (ItemDTO itemDTO : itemList) {
        if (itemDTO.getTotal() == null) {
            continue;
        }
        itemDTO.setLabel(itemLabelMap.getOrDefault(itemDTO.getCode(), itemDTO.getCode()));

        Double divide = divide(itemDTO.getTotal().toString(), sum.toString(), 4);
        itemDTO.setRate(divide);
        itemDTO.setPercentRate(toPercent(divide));
    }

    // 缺失项补位
    List codeList = itemList.stream().map(ItemDTO::getCode).collect(Collectors.toList());
    List labelList = new ArrayList(itemLabelMap.keySet());
    labelList.removeAll(codeList);
    for (String code : labelList) {
        String label = itemLabelMap.getOrDefault(code, code);
        ItemDTO itemDTO = new ItemDTO(code, label, 0L, "0.00%", 0.0);
        itemList.add(itemDTO);
    }
}
@Data
public class ItemDTO {

    private String code;
    private String label;
    private Long total;
    private String percentRate;
    private Double rate;

    public ItemDTO() {
    }

    public ItemDTO(String code, String label, Long total, String percentRate, Double rate) {
        this.code = code;
        this.label = label;
        this.total = total;
        this.percentRate = percentRate;
        this.rate = rate;
    }
}
public static Double divide(String dividend, String divisor, Integer scale) {
    return divide(dividend, divisor, scale, BigDecimal.ROUND_HALF_UP);
}

public static Double divide(String v1, String v2, Integer scale, Integer roundingMode) {
    if (StringUtils.isBlank(v1) || StringUtils.isBlank(v2) || "0".equals(v1)) {
        return 0D;
    }

    BigDecimal b1 = new BigDecimal(v1);
    BigDecimal b2 = new BigDecimal(v2);
    return b1.divide(b2, scale, roundingMode).doubleValue();
}

/**
 * 百分数
 */
public static String toPercent(Double value) {
    DecimalFormat decimalFormat = new DecimalFormat("#0.00%");
    return decimalFormat.format(value);
}

【信息由网络或者个人提供,如有涉及版权请联系COOY资源网邮箱处理】

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容