Create a third array list by summing up data related to same element if present in both lists, else insert the new data
I created two maps from the two array lists with Id as key and then created a set by combining keys from both maps. Making use of the values in set, i queried both the lists and arrived at the sum. I am seeing the expected output if i follow this method, but wanted to know if there is any other efficient way of achieving this in Java 1.6
----------------Java----------------
public class Stock {
private int stockCode;
private int stockQuantity;
private int stockValue;
public int getStockCode() {
return stockCode;
}
public int getStockQuantity() {
return stockQuantity;
}
public int getStockValue() {
return stockValue;
}
public Stock(int stockCode, int stockQuantity, int stockValue) {
this.stockCode = stockCode;
this.stockQuantity = stockQuantity;
this.stockValue = stockValue;
}
public static void main(String[] args){
List<Stock> oldStock = new ArrayList<Stock>();
Stock s1 = new Stock(1, 20, 16000);
Stock s2 = new Stock(2, 10, 5000);
Stock s3 = new Stock(3, 15, 3000);
oldStock.add(s1);
oldStock.add(s2);
oldStock.add(s3);
List<Stock> newStock = new ArrayList<Stock>();
Stock s4 = new Stock(5, 5, 2500);
Stock s5 = new Stock(1, 10, 8000);
Stock s6 = new Stock(3, 10, 2000);
newStock.add(s4);
newStock.add(s5);
newStock.add(s6);
List<Stock> netStock = new ArrayList<Stock>();
Map<Integer, Stock> oldStockMap = new HashMap<Integer, Stock>();
for(Stock os:oldStock){
oldStockMap.put(os.getStockCode(),os);
}
Map<Integer, Stock> newStockMap = new HashMap<Integer, Stock>();
for(Stock ns:newStock){
newStockMap.put(ns.getStockCode(),ns);
}
Set<Integer> keySet = new HashSet<Integer>();
keySet.addAll(oldStockMap.keySet());
keySet.addAll(newStockMap.keySet());
for(Integer ks:keySet){
Integer netStockQ=0;
Integer netStockV=0;
if(oldStockMap.get(ks)!=null && newStockMap.get(ks)!=null) {
netStockQ =oldStockMap.get(ks).getStockQuantity() + newStockMap.get(ks).getStockQuantity();
netStockV = oldStockMap.get(ks).getStockValue() + newStockMap.get(ks).getStockValue();
} else if(oldStockMap.get(ks)==null && newStockMap.get(ks)!=null){
netStockQ = newStockMap.get(ks).getStockQuantity();
netStockV = newStockMap.get(ks).getStockValue();
} else if(oldStockMap.get(ks)!=null && newStockMap.get(ks)==null){
netStockQ =oldStockMap.get(ks).getStockQuantity();
netStockV = oldStockMap.get(ks).getStockValue();
}
netStock.add(new Stock(ks,netStockQ, netStockV));
}
for(Stock ns: netStock){
System.out.println(ns.getStockCode() +"- Quantity - "+ ns.getStockQuantity()+"- Value -"+ns.getStockValue());
}
}
}
---------------Output---------------
1- Quantity - 30- Value -24000
2- Quantity - 10- Value -5000
3- Quantity - 25- Value -5000
5- Quantity - 5- Value -2500
new HashMap<>()) in your code, which are only supported after Java 7?