我有一个对象(EnergyUsageData
),它表示每种能源类型的能源使用情况,它有两个字段:
private EnergyType type;
private Map<YearMonth, BigDecimal> billsMap;
该地图包含能源账单数据。我正在获取能源账单数据,并将其放入一个列表中:
List<EnergyUsageData> energyUsageDataList = new ArrayList<>();
现在我想为那些具有相同能量类型的人组合贴图。例如,如果我在柴油能源类型的列表中有多个元素,我想组合它们的billsMap
,并添加相同YearMonth
的能源使用情况。我正在寻找一种有效的方法来组合数据并生成一个列表,其中每个能源类型只有一个元素。做这件事最好的方法是什么?
发布于 2015-11-22 12:47:14
伪码:
For all keys in table 2
v2 = that key's value in table 2.
v1 = that key's value in table 1.
If v1 is null
Set key and v2 pair into table 1.
Otherwise
Sum the two values
Set key and sum pair in table 1.
Done.
发布于 2015-11-22 14:35:21
使用Java 8 streams,您可以像这样高效地完成这项工作。
public static List<EnergyUsageData> process(final Collection<EnergyUsageData> data) {
final Map<EnergyType, Map<YearMonth, BigDecimal>> tempMap = new HashMap<>();
final List<EnergyUsageData> energyUsageData = data.stream()
.flatMap(d -> d.getBillsMap().entrySet().stream().map(
dd -> new FlatData(d.getType(), dd.getKey(), dd.getValue())))
.filter(d -> {
final Map<YearMonth, BigDecimal> map = tempMap.get(d.type);
if (map != null) {
final BigDecimal amount = map.get(d.yearMonth);
map.put(d.yearMonth, amount.add(d.amount));
return false;
}
return true;
})
.map(d -> {
final HashMap<YearMonth, BigDecimal> billsMap = new HashMap<>();
billsMap.put(d.yearMonth, d.amount);
tempMap.put(d.type, billsMap);
return new EnergyUsageData(d.type, billsMap);
//Assuming Constructor of EnergyUsageData will hold
// the reference of billsMap and will not copy billsMap
})
.collect(Collectors.toList());
return energyUsageData;
}
final class FlatData {
public final EnergyType type;
public final YearMonth yearMonth;
public final BigDecimal amount;
FlatData(EnergyType type, YearMonth yearMonth, BigDecimal amount) {
this.type = type;
this.yearMonth = yearMonth;
this.amount = amount;
}
}
它将一个接一个地处理值,并在整个集合中循环一次。
https://stackoverflow.com/questions/33851292
复制相似问题