我有class
class cust{
private String name;
private int id;
//Getter and setters
//equals
//hashcode
//toString
}
在我的主要类中
List<Customer> custList = new ArrayList<Customer>;
Custlist在其中添加了独特的客户。
如果我将新客户添加到列表中,我需要用相同的旧客户和使用beanutils替换旧客户。
这是我的Beanutils代码
BeanUtils.setProperty("customer", "custList[0]", customer);
ps:我有超越&amp;hashcode方法。
为什么要使用beanutils?
为什么不只是在列表中找到元素并覆盖它?
public void addOrReplace(List<Customer> customers, Customer customer) {
int index = -1;
for(int k = 0; index != -1 && k < customers.size(); k++) {
if(customers.get(k).getId() == customer.getId()) {
index = k;
}
}
if(index == -1) {
customers.add(customer);
} else {
customers.set(index, customer);
}
}
我同意bretc的答案的观点,但是我的实现更简洁,并且原始列表未触及:
public List<Customer> addOrReplace(List<Customer> customers, Customer customer) {
return customers.stream()
.map(c -> c.getId() == customer.getId() ? customer : c)
.collect(Collectors.toList());
}