下面是一个样本列表项目。它包含1 * 10 = 10(计数*货币=小计) 如果货币相同,我想添加计数,子总数。
例如
1 * 10 = 10
3 * 10 = 30
列表检查后,最后的lsit必须是
4 * 10 = 40.
public class CashModal {
private int count;
private int currency;
private int subTotal;
gettter/setter
}
listItems.add("1 * 10 = 10");
listItems.add("2 * 10 = 20");
listItems.add("1 * 5 = 5");
listItems.add("2 * 10 = 20");
cashModals=new ArrayList<CashModal>();
for(String s:listItems){
cashModal=new CashModal();
String x[]=s.split("\\*");
cashModal.setCount(Integer.parseInt(x[0].trim()));
cashModal.setCurrency(Integer.parseInt(x[1].split("\\=")[0].trim()));
cashModal.setSubTotal(Integer.parseInt(x[1].split("\\=")[1].trim()));
cashModals.add(cashModal);
subTotal=subTotal+Integer.parseInt((x[1].split("\\=")[1]).trim());
}
答案 0 :(得分:1)
使用地图维护数据。密钥是货币字段。请尝试以下代码:
ArrayList<String> listItems = new ArrayList<String>();
listItems.add("1 * 10 = 10");
listItems.add("2 * 10 = 20");
listItems.add("1 * 5 = 5");
listItems.add("2 * 10 = 20");
Map<Integer, CashModal> cashModalsMap = new HashMap<Integer, CashModal>();
int subTotal = 0;
int existingCount = 0;
int existingSubtotal = 0;
for (String s : listItems) {
String x[] = s.split("\\*");
if (!cashModalsMap
.containsKey(Integer.parseInt(x[1].split("\\=")[0].trim()))) {
CashModal cashModal = new CashModal();
cashModal.setCount(Integer.parseInt(x[0].trim()));
cashModal.setCurrency(Integer.parseInt(x[1].split("\\=")[0]
.trim()));
cashModal.setSubTotal(Integer.parseInt(x[1].split("\\=")[1]
.trim()));
cashModalsMap.put(
Integer.parseInt(x[1].split("\\=")[0].trim()),
cashModal);
subTotal = subTotal
+ Integer.parseInt((x[1].split("\\=")[1]).trim());
} else {
CashModal cashModalExisting = cashModalsMap.get(Integer
.parseInt(x[1].split("\\=")[0].trim()));
existingCount = cashModalExisting.getCount();
existingSubtotal = cashModalExisting.getSubTotal();
cashModalExisting.setCount(existingCount
+ Integer.parseInt(x[0].trim()));
cashModalExisting.setSubTotal(existingSubtotal
+ Integer.parseInt(x[1].split("\\=")[1].trim()));
cashModalsMap.put(
Integer.parseInt(x[1].split("\\=")[0].trim()),
cashModalExisting);
}
}
for(CashModal cm:cashModalsMap.values()){
System.out.println("Count:"+cm.getCount()+",Currency:"+cm.getCurrency()+",SubTotal:"+cm.getSubTotal());
}
}