如何修改数组列表中的元素

时间:2017-03-10 16:52:22

标签: java arraylist

我创建了以下arrayLIST。我想修改djohn@gmail.com的电话号码。你能告诉我如何修改它吗?提前致谢

 private static List<Customer> customers;
{
    customers = new ArrayList();
    customers.add(new Customer(101, "John", "Doe", "djohn@gmail.com", "121-232-3435"));
    customers.add(new Customer(201, "Russ", "Smith", "sruss@gmail.com", "343-545-2345"));
    customers.add(new Customer(301, "Kate", "Williams", "kwilliams@gmail.com", "876-237-2987"));

}

3 个答案:

答案 0 :(得分:3)

使用Java 8流,使用谓词查找客户,使用Optional.ifPresent()更新值。

customers.stream()
         .filter(customer -> "djohn@gmail.com".equals(customer.getEmail()))
         .findFirst()
         .ifPresent(customer -> customer.setPhoneNumber(2222222));

答案 1 :(得分:2)

假设您有getter和setter,请在电子邮件与您想要的电子邮件匹配时遍历列表并更新电话号码

for (Customer customer : customers){
    if (customer.getEmail().equals("djohn@gmail.com")){
        customer.setPhoneNumber("xxx-xxx-xxxx");
    }
} 

答案 2 :(得分:0)

与@Sean Patrick Floyd提供的解决方案类似,如果您想要通过电子邮件修改所有客户&#34; djohn@gmail.com":

customers.stream().filter(e -> "djohn@gmail.com".equals(e.getEmail()))
                  .forEach(e -> e.setPhoneNumber("xxx-xxx-xxxx"));