Stream根据不同的条件对不同的字段进行过滤和求和
Stream to filter and sum different fields depending on different conditions
我有一个列表:
ID | Product Code | Product Type | Transaction Amt | Charges Amt | Charges ID
1 | 001 | 001 | 10.00 | 0.01 | 001
2 | 001 | 001 | 11.00 | 0.01 | 001
3 | 002 | 001 | 12.00 | 0.01 | 002
我想要这样的结果:
ID | Product Code | Product Type | Transaction Amt | Charges Amt | Charges ID
1 | 001 | 001 | 21.00 | 0.01 | 001
3 | 002 | 001 | 12.00 | 0.01 | 002
我想对交易金额和手续费进行汇总,但是当手续费id相同时,我只会计算一次。
下面是根据产品代码和类型总结的代码:
Map<String, Transaction> map = txs.stream()
.map(s -> {
s.setTotalCount(1);
return s;
})
.collect(Collectors.toMap(f -> f.getProductCode() + f.getProductType()
Function.identity(),
(s, a) -> new FeeAllocationTransactionModel(
s.getProductCode(),
s.getProductType(),
s.getTranzAmt().add(a.getTranzAmt()),
s.getCharges().add(a.getFeeCharges()),
s.getTotalCount() + 1
)));
List<Transaction> reduced = new ArrayList<>(map.values());
从上面的代码我得到:
ID | Product Code | Product Type | Transaction Amt | Charges Amt | Charges ID
1 | 001 | 001 | 21.00 | **0.02** | 001
3 | 002 | 001 | 12.00 | 0.01 | 002
您可以检查您的 mergeFunction 中的费用 ID Collectors.toMap
:
(s, a) -> {
double charges = (s.getChargesId().equals(a.getChargesId())
? s.getCharges()
: s.getCharges().add(a.getFeeCharges());
return new FeeAllocationTransactionModel(
s.getProductCode(),
s.getProductType(),
s.getTranzAmt().add(a.getTranzAmt()),
charges,
s.getTotalCount() + 1);
}
我有一个列表:
ID | Product Code | Product Type | Transaction Amt | Charges Amt | Charges ID
1 | 001 | 001 | 10.00 | 0.01 | 001
2 | 001 | 001 | 11.00 | 0.01 | 001
3 | 002 | 001 | 12.00 | 0.01 | 002
我想要这样的结果:
ID | Product Code | Product Type | Transaction Amt | Charges Amt | Charges ID
1 | 001 | 001 | 21.00 | 0.01 | 001
3 | 002 | 001 | 12.00 | 0.01 | 002
我想对交易金额和手续费进行汇总,但是当手续费id相同时,我只会计算一次。
下面是根据产品代码和类型总结的代码:
Map<String, Transaction> map = txs.stream()
.map(s -> {
s.setTotalCount(1);
return s;
})
.collect(Collectors.toMap(f -> f.getProductCode() + f.getProductType()
Function.identity(),
(s, a) -> new FeeAllocationTransactionModel(
s.getProductCode(),
s.getProductType(),
s.getTranzAmt().add(a.getTranzAmt()),
s.getCharges().add(a.getFeeCharges()),
s.getTotalCount() + 1
)));
List<Transaction> reduced = new ArrayList<>(map.values());
从上面的代码我得到:
ID | Product Code | Product Type | Transaction Amt | Charges Amt | Charges ID
1 | 001 | 001 | 21.00 | **0.02** | 001
3 | 002 | 001 | 12.00 | 0.01 | 002
您可以检查您的 mergeFunction 中的费用 ID Collectors.toMap
:
(s, a) -> {
double charges = (s.getChargesId().equals(a.getChargesId())
? s.getCharges()
: s.getCharges().add(a.getFeeCharges());
return new FeeAllocationTransactionModel(
s.getProductCode(),
s.getProductType(),
s.getTranzAmt().add(a.getTranzAmt()),
charges,
s.getTotalCount() + 1);
}