多个属性组成的对象作为Map集合的唯一key,自动实现数据的分组统计

项目有需求,在解析文件的时候,需要按照某几个字段作为唯一值,统计对应的总费用是多少,那么需要用到Map集合,Key使用这几个字段组成的对象,value就是对应的费用。

1、首先需要将某几个字段拼装的对象重写hash 和 equals方法,保证只要是相同字段值组成的对象key是唯一的:

package com.lenovo.mcmp.cost.etl.model;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.Serializable;
import java.util.Objects;

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class AwsPrivateRateDiscountMapKey implements Serializable {

    private String cloudAccountId;

    private String reservationSubscriptionId;

    private String productCode;

    private String operation;

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        AwsPrivateRateDiscountMapKey that = (AwsPrivateRateDiscountMapKey) o;
        return Objects.equals(cloudAccountId, that.cloudAccountId) && Objects.equals(reservationSubscriptionId, that.reservationSubscriptionId) && Objects.equals(productCode, that.productCode) && Objects.equals(operation, that.operation);
    }

    @Override
    public int hashCode() {
        return Objects.hash(cloudAccountId, reservationSubscriptionId, productCode, operation);
    }
}

2、其次处理集合自动累加费用:

CsvReader csvReader = null;//文件的行对象
AwsPrivateRateDiscountMapKey key = new AwsPrivateRateDiscountMapKey(cloudAccountId, reservationSubscriptionId, productCode, operation);
        privateRateDiscountMap.merge(key, resolveUnblendedCost(csvReader), BigDecimal::add);
        //行对象中取出对应的费用数据逻辑
private static BigDecimal resolveUnblendedCost(CsvReader csvReader) throws IOException {
        return new BigDecimal(csvReader.get("lineItem/xxx"));
    }

通过上述处理,就实现了将几个属性作为key对象,自动实现对应的费用总值的累加,帮我们自动拼装成Map集合!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值