I have an ArrayList with one String value and two Integer values. I want the sum of integers under the same String value. For example
aaa , 1 , 2aaa , 2 , 1bbb , 1 , 2ccc , 3 , 3ccc , 1 , 2ccc , 2 , 2
So final list should come as
aaa , 3, 3bbb , 1, 2ccc , 6, 7
I was able to get the sum using one String and one Integer.
this is what i used for one String and one Integer.
ArrayList<InvoiceData> invoiceHeaderList = new ArrayList<>();
invoiceHeaderList.clear();
Map<String, Integer> sumMap = new TreeMap<String, Integer>();
for (ItemData dashboardOneData : invoiceList) {
String key = dashboardOneData.getInvoiceNo() + "#" + dashboardOneData.getInvoiceDate();
if (sumMap.containsKey(key)) {
int sum = sumMap.get(key);
sum += dashboardOneData.getMatQty();
sumMap.put(key, sum);
} else {
sumMap.put(key, dashboardOneData.getMatQty());
}
}
for (Map.Entry<String, Integer> e : sumMap.entrySet()) {
String[] splitInvoice;
InvoiceData invTempData = new InvoiceData();
if (e.getKey() != null || !e.getKey().equals("")) {
splitInvoice = e.getKey().split("#+");
invTempData.setInvoiceNo(splitInvoice[0]);
invTempData.setInvoiceDate(splitInvoice[1]);
invTempData.setInvoiceQty(e.getValue());
invoiceHeaderList.add(invTempData);
}
}
I tried to do as below but no luck, I was not able to take the sum of the two integers inside the method.
public class QuantityData {
private int oriQty;
private int newQty;
public QuantityData() {
}
}
Method....
ArrayList<InvoiceData> invoiceHeaderList = new ArrayList<>();
invoiceHeaderList.clear();
Map<String, List<QuantityData>> sumMap = new TreeMap<String, List<QuantityData>>();
for (ItemData dashboardOneData : invoiceList) {
String key = dashboardOneData.getInvoiceNo() + "#" + dashboardOneData.getInvoiceDate();
QuantityData qtyData = new QuantityData();
if (sumMap.containsKey(key)) {
ArrayList<QuantityData> qtyArrayList = new ArrayList<>();
qtyArrayList.add(qtyData);
sumMap.put(key, qtyArrayList);
} else {
ArrayList<QuantityData> qtyArrayList = new ArrayList<>();
qtyData.setOriQty(dashboardOneData.getMatQty());
qtyData.setNewQty(dashboardOneData.getNewMatQty());
qtyArrayList.add(qtyData);
sumMap.put(key, qtyArrayList);
}
}
for (Map.Entry<String, List<QuantityData>> e : sumMap.entrySet()) {
String[] splitInvoice;
InvoiceData invTempData = new InvoiceData();
if (e.getKey() != null || !e.getKey().equals("")) {
}
}