我有一个像这样的数组列表结构:
ArrayList<Arraylisttableitem> tablestatuslist = new ArrayList<Arraylisttableitem>();
此数组列表的模型类如下所述:
public class Arraylisttableitem {
String total, noofcustomer, firstname, tab_name, balance, time;
public Arraylisttableitem(String total, String noofcustomer,
String firstname, String tab_name, String balance, String time) {
// TODO Auto-generated constructor stub
this.total = total;
this.noofcustomer = noofcustomer;
this.firstname = firstname;
this.tab_name = tab_name;
this.balance = balance;
this.time = time;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getNoofcustomer() {
return noofcustomer;
}
public void setNoofcustomer(String noofcustomer) {
this.noofcustomer = noofcustomer;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getTab_name() {
return tab_name;
}
public void setTab_name(String tab_name) {
this.tab_name = tab_name;
}
public String getBalance() {
return balance;
}
public void setBalance(String balance) {
this.balance = balance;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
在名为 tab_name 的元素中,我可能有重复的元素。我想识别重复的元素并添加所有重复的值。例如,tab_num 10 的余额为 5,tab_num 10 的余额为 10。我想要的是 tab_nam 10 应该出现一次,余额应该为 15,列表中没有任何重复值。
如何解决这个问题?
我不知道里面该写什么..
for(Arraylisttableitem itemlist : tablestatuslist)
{
}
我的 JSON 有重复值,因此我的数组列表支持重复值。
如果您想添加值,那么最好将字段类型保留为 int 而不是 string。但就你而言,你可以这样做
Map<String, Arraylisttableitem> map = new HashMap<String, Arraylisttableitem>();
for(Arraylisttableitem item : tableStatusList){
Arraylisttableitem prevItem = map.get(item.getTab_name());
if(prevItem != null){
prevItem.setTotal(String.valueOf(Integer.parseInt(item.getTotal()) + Integer.parseInt(prevItem.getTotal())));
prevItem.setBalance(String.valueOf(Integer.parseInt(item.getBalance()) + Integer.parseInt(prevItem.getBalance())));
prevItem.setNoofcustomer(String.valueOf(Integer.parseInt(item.getNoofcustomer()) + Integer.parseInt(prevItem.getNoofcustomer())));
prevItem.setTime(String.valueOf(Integer.parseInt(item.getTime()) + Integer.parseInt(prevItem.getTime())));
map.put(item.getTab_name(), prevItem);
} else {
map.put(item.getTab_name(), item);
}
}
tableStatusList = new ArrayList<Arraylisttableitem>(map.values());
对每个项目使用HashMap。当您“放置”一个项目到地图时,它会返回之前存储在那里的旧项目。所以这是你可以将两者结合起来的地方。