Код: Выделить всё
List incomingTransactions = new ArrayList();
incomingTransactions.add(new FinancialTransaction(1, 1, 2, 1000000));
incomingTransactions.add(new FinancialTransaction(2, 1, 2, 2000000));
incomingTransactions.add(new FinancialTransaction(3, 2, 1, 1000000));
incomingTransactions.add(new FinancialTransaction(4, 2, 1, 4000000));
incomingTransactions.add(new FinancialTransaction(5, 2, 3, 1000000));
< /code>
FinancialTransaction Pojo: < /p>
public class FinancialTransaction {
private Integer id;
private Integer srcId;
private Integer dstId;
private Long amount;
public Integer getId() {
return id;
}
//getters, setters, constructors, toString
}
Код: Выделить всё
public class TransactionMerger {
public static Map mergeTransactions(List financialTransactions) {
Map mergedTransactions = new HashMap();
for (FinancialTransaction ft: financialTransactions) {
String key = ft.getSrcId() + "" + ft.getDstId();
if (mergedTransactions.get(key) != null) {
mergedTransactions.put(key, ft);
} else {
// Don't know to write here :/
}
}
financialTransactions.clear();
return mergedTransactions;
}
}
Key: 12 Value: FinancialTransaction {12, 1, 2, 3000000} //summed first and second values in incoming list
Key: 21 Value: FinancialTransaction {21, 2, 1, 5000000} //summed third and fourth values in incoming list
Key: 23 Value: FinancialTransaction {23, 2, 3, 1000000} //returned fifth values
< /code>
У меня нет идей. Я уже знаю, как группироваться с композитным ключом, от нескольких значений, но как суммировать и группировать - у меня нет идей.
Как я могу это сделать?
Подробнее здесь: https://stackoverflow.com/questions/618 ... va-objects