我有交易列表,每个交易都有一些属性,例如现在的来源,从交易列表中,我想获取具有相同来源值(value)的所有交易,并将它们组合成一个交易,例如
tradeName quote source quantity price
Google GOOG Goldman Sachs 15 610
Microsoft MSFT Barclays 400 28
Google GOOG Goldman Sachs 45 610
Google GOOG Goldman Sachs 40 610
Microsoft MSFT Barclays 1000 28
现在根据源信息,我应该合并交易,所以我更新的交易列表将是
tradeName quote source quantity price
Google GOOG Goldman Sachs 100 610
Microsoft MSFT Barclays 1400 28
我不确定比较部分,如何解决?
<小时/>尝试了以下方法,
for (Trade trade : tradeList)
{
//Not sure how to compare this.trade.source with all sources
//of all trades present in the trade.
//Logic should be if source matches then quantity should be added
//but am not sure how comparison would work.
}
Class Trade
{
private tradeName;
private quote;
private source;
private quantity;
private price;
//Getters and Setters for each of above mentioned attributes.
}
最佳答案
我想我会创建一个 HashMap<String, Trade>
,使用tradeName+quote+source
作为键,然后将列表中的每个交易添加到 map 中的相应项目。
示例:
Map<String, Trade> map = new HashMap<String, Trade>();
for (Trade trade : tradeList) {
String key = trade.tradeName + "#" + trade.quote + "#" + trade.source; // signature, what you merge by
if (map.containsKey(key)) {
map.put(key, trade); // the first trade with such a signature
} else {
// not the first, so merge it with the existing one
map.get(key).add(trade); // you'll have to implement the Trade.add() method
}
}
List<Trade> merged = new LinkedList<Trade>(map.values());
关于java - 如果数组列表中满足条件,如何比较元素并合并?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11781330/