java - 如果数组列表中满足条件,如何比较元素并合并?

标签 java

我有交易列表,每个交易都有一些属性,例如现在的来源,从交易列表中,我想获取具有相同来源值(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/

相关文章:

java - 方法引用语法如何在 Java 8 中工作

java - 删除链表的最后一个节点

java - 将捕获的 Fiddler 请求转换为 Java

java - java中索引越界异常

java - 从选定的 ListViewItem 文本填充 TextView

java - Java中的继承问题

java - GUI 之外的新线程

java - DateUtils 使用哪个时区?

java - 对于错误的配置抛出未经检查的异常是一个好主意吗?

java - 无法让 Spring Boot 应用程序在 Google Cloud Platform 灵活环境上运行