0

i have list of trades, each trades has some attributes like source now, from the list of trades, i want to get all trades that have same source value and combine them together into one trade, for example

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

now based on source information, i should combine trades, so my updated list of trade would be

tradeName      quote           source            quantity        price 
Google          GOOG           Goldman Sachs        100           610  
Microsoft       MSFT           Barclays             1400           28

I am not sure about comparison part, how to go about solving it?


Tried following approach,

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. 

}
12
  • What have you tried? Do you need to know how to write the loop? The comparison within the loop? What precisely do you need to know? A pseudocode algorithm? Commented Aug 2, 2012 at 15:59
  • @ngmiceli : I am iterating through the loop but now how would i do comparison within the loop with all the elements of the arraylist, this is where am hung up. Commented Aug 2, 2012 at 16:00
  • If you show us what you've written so far for iterating through the loop, we can better help Commented Aug 2, 2012 at 16:01
  • @ngmiceli: added updates to question. Commented Aug 2, 2012 at 16:03
  • 1
    Thanks- one more question. How is a trade represented? I would think each trade is its own Trade object that you defined, but String[] trade in your loop suggests otherwise Commented Aug 2, 2012 at 16:05

4 Answers 4

3

I think I'd create a HashMap<String, Trade>, using tradeName+quote+source as a key, then add each trade from the list to the appropriate item in the map.

Example:

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());
Sign up to request clarification or add additional context in comments.

4 Comments

can you provide more detailed example
ladies and gentlemen, please comment when downvoting.
@Rachel check the edit. This assumes, of course, that the pound symbol ("#") does not occur in either of the key fields. If it does, pick one that does not.
@Qnan shouldn't line 4 be this: if (!map.containsKey(key)) {
1

While I would agree that using a Hashmap could be more efficient, I prefer trying to keep to the O.P's provided method. If we're going to iterate over every member, let's check if we've found that member so far. If so, modify him. If not, add him. I suggest doing all of this to a new list, then doing whatever you want with the new list (setting the old to the new, printing the new, emailing the new to the president of Russia, whatever).

So how about something like follows? (I didn't compile this so excuse any typos)

//Create a new list to store our "simplified" results into
ArrayList<Trade> newTradeList = new ArrayList<Trade>(tradeList.size());

//For each trade in the old list, call it "trade" and...
for(Trade trade : tradeList){

    //First we ask, is there already a trade in this list with the same source?
    //indexOf finds where in the array the element lives. I store that result in index
    int index = newTradeList.indexOf(trade);

    //If the element isn't in our list yet, indexOf will return -1.
    //If the result is NOT -1, then we have already seen a trade with this source before
    if(index != -1) {
         //In that case, get that element. We know what index it lives at so grab it.
         Trade t = newTradeList.get(index);
         //Then, do whatever operations to combine the two trades. I assumed you add the quantities. 
         //So the trade in our new list's quantity should be what it was, plus the new trade's quantity
         t.setQuantity(t.getQuantity() + trade.getQuantity());
    } 

    //But if we have never seen this source before, let's add it to our our new list
    else {
         newTradeList.add(trade);
    }
}

This is, of course, making a few assumptions. In order for .indexOf to work, you'll need your Trade class to have the equals method defined appropriately (check if source, or source and price are the same- whatever seems right). If you redefine equals, you really should also define hashCode. It also assumed you have a method .addQuantity just because it made the code cleaner than a combination of gets and sets.


HashMap's have the advantage of nearly instant (O(1)) checks to see if an element already exists, and ensures that elements in it are unique (as a hashmap is a Set, and a set can not have duplicate elements). The code would look pretty similar, except we could take advantage of HashMap's containsKey method, rather than indexOf.

2 Comments

i can change it to hashMap, i do not have any such constraints.
If you can let me know what line(s) in particular, maybe I could better help?
0

Please, check this 2 approaches:

Java Bean:

public class Trade {

private String tradeName;
private String quote;
private String source;
private Integer quantity;
private Integer price;

public String getTradeName() {
    return tradeName;
}

public void setTradeName(String tradeName) {
    this.tradeName = tradeName;
}

public String getQuote() {
    return quote;
}

public void setQuote(String quote) {
    this.quote = quote;
}

public String getSource() {
    return source;
}

public void setSource(String source) {
    this.source = source;
}

public Integer getQuantity() {
    return quantity;
}

public void setQuantity(Integer quantity) {
    this.quantity = quantity;
}

public Integer getPrice() {
    return price;
}

public void setPrice(Integer price) {
    this.price = price;
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((source == null) ? 0 : source.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Trade other = (Trade) obj;
    if (source == null) {
        if (other.source != null)
            return false;
    } else if (!source.equals(other.source))
        return false;
    return true;
}

@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("Trade [tradeName=");
    builder.append(tradeName);
    builder.append(", quote=");
    builder.append(quote);
    builder.append(", source=");
    builder.append(source);
    builder.append(", quantity=");
    builder.append(quantity);
    builder.append(", price=");
    builder.append(price);
    builder.append("]");
    return builder.toString();
}
}

-- EDIT --

Check this, it's just quite simple:

import java.util.ArrayList;
import java.util.List;

public class TradeTest {

/**
 * @param args
 */
public static void main(String[] args) {
    Trade t1 = new Trade();
    t1.setPrice(610);
    t1.setQuantity(15);
    t1.setQuote("GOOG");
    t1.setSource("Goldman Sachs");
    t1.setTradeName("Google");

    Trade t2 = new Trade();
    t2.setPrice(28);
    t2.setQuantity(400);
    t2.setQuote("MSFT");
    t2.setSource("Barclays");
    t2.setTradeName("Microsoft");

    Trade t3 = new Trade();
    t3.setPrice(610);
    t3.setQuantity(45);
    t3.setQuote("GOOG");
    t3.setSource("Goldman Sachs");
    t3.setTradeName("Google");

    Trade t4 = new Trade();
    t4.setPrice(610);
    t4.setQuantity(40);
    t4.setQuote("GOOG");
    t4.setSource("Goldman Sachs");
    t4.setTradeName("Google");

    Trade t5 = new Trade();
    t5.setPrice(28);
    t5.setQuantity(1000);
    t5.setQuote("MSFT");
    t5.setSource("Barclays");
    t5.setTradeName("Microsoft");

    List<Trade> trades = new ArrayList<Trade>();
    trades.add(t1);
    trades.add(t2);
    trades.add(t3);
    trades.add(t4);
    trades.add(t5);

    List<Trade> googleTrades = new ArrayList<Trade>();
    List<Trade> microsoftTrades = new ArrayList<Trade>();

    Integer googleQuantities = 0;
    Integer microsoftQuantities = 0;

    for (Trade trade : trades) {
        if (trade.getSource().equals("Goldman Sachs")) {
            googleTrades.clear();
            googleQuantities += trade.getQuantity();
            trade.setQuantity(googleQuantities);
            googleTrades.add(trade);
        } else if (trade.getSource().equals("Barclays")) {
            microsoftTrades.clear();
            microsoftQuantities += trade.getQuantity();
            trade.setQuantity(microsoftQuantities);
            microsoftTrades.add(trade);
        }
    }

    System.out.println("Google trades: \n");
    System.out.println(googleTrades);
    System.out.println("\n");
    System.out.println("Microsoft trades: \n");
    System.out.println(microsoftTrades);

}

}

Check if this works for you.

Comments

-1

I feel this should do.

Trade gsTrades = new Trade();
    Trade barclaysTrades = new Trade();

    for(Trade trade: tradeList){
        if(trade.getSource().equals("GS")){
            gsTrades.setQuantity(gsTrades.getQuantity()+trade.getQuantity());
            gsTrades.setPrice(gsTrades.getPrice()+trade.getPrice());
        }else{
            barclaysTrades.setQuantity(barclaysTrades.getQuantity()+trade.getQuantity());
            barclaysTrades.setPrice(barclaysTrades.getPrice()+trade.getQuantity());
        }
    }
    System.out.println("GS trade details = " + gsTrades.toString());
    System.out.println("Barclays trade details = " + barclaysTrades.toString());

1 Comment

This would not work as i have only shared an example here and my list has like 1000 trades and need to compare and merge trades based on same source entry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.