1

I have created the below arrayLIST . I want to modify the phone number of [email protected]. Can you please let me know how to modify it. Thanks in advance

 private static List<Customer> customers;
{
    customers = new ArrayList();
    customers.add(new Customer(101, "John", "Doe", "[email protected]", "121-232-3435"));
    customers.add(new Customer(201, "Russ", "Smith", "[email protected]", "343-545-2345"));
    customers.add(new Customer(301, "Kate", "Williams", "[email protected]", "876-237-2987"));

}
3
  • docs.spring.io/spring-framework/docs/current/javadoc-api/org/… ? Commented Mar 10, 2017 at 16:55
  • you have to have a customer dao method for update, then get customer based on id, and then update the fields passed by patch. Commented Mar 10, 2017 at 16:58
  • customers.get(0).setPhoneNumber("xxx-xxx-xxxx"); assuming Customer class has getters and setters. Commented Mar 10, 2017 at 17:19

3 Answers 3

3

With Java 8 streams, use a predicate to find the customer, and Optional.ifPresent() to update the value.

customers.stream()
         .filter(customer -> "[email protected]".equals(customer.getEmail()))
         .findFirst()
         .ifPresent(customer -> customer.setPhoneNumber(2222222));
Sign up to request clarification or add additional context in comments.

Comments

2

Assuming you have getters and setters, loop through the list and update the phone number when the e-mail matches the one you want

for (Customer customer : customers){
    if (customer.getEmail().equals("[email protected]")){
        customer.setPhoneNumber("xxx-xxx-xxxx");
    }
} 

Comments

0

Similar with the solution provided by @Sean Patrick Floyd, if you want want to modify all the customers with email "[email protected]":

customers.stream().filter(e -> "[email protected]".equals(e.getEmail()))
                  .forEach(e -> e.setPhoneNumber("xxx-xxx-xxxx"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.