2016-12-02 37 views
0

我有类如何使用BeanUtils的替代Java的ArrayList中元素的现有价值

class cust{ 
private String name; 
private int id; 

//Getter and setters 
//equals 
//hashcode 
//toString 
} 

在我的主类

List<Customer> custList = new ArrayList<Customer>; 

CUSTLIST具有独特的客户在它补充说。

如果我将新客户添加到列表中,我需要使用beanutils替换具有相同ID和ID的旧客户。

这是我的BeanUtils代码

BeanUtils.setProperty("customer", "custList[0]", customer); 

PS:我已经重写等于& hashCode方法。

回答

0

为什么你必须使用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); 
    } 
} 
+0

我实现只用BeanUtils的。为了更好的理解,我简化了上面的例子。 – Ijaz

0

我同意BretC的答案的要点,但我的实现更加简洁并保持原始列表不变:

public List<Customer> addOrReplace(List<Customer> customers, Customer customer) { 
    return customers.stream() 
      .map(c -> c.getId() == customer.getId() ? customer : c) 
      .collect(Collectors.toList()); 
} 
相关问题