项目有需求,在解析文件的时候,需要按照某几个字段作为唯一值,统计对应的总费用是多少,那么需要用到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集合!