Java – How to view different parameters of an object from the same method?

How to view different parameters of an object from the same method?… here is a solution to the problem.

How to view different parameters of an object from the same method?

I have a contact human with a name, email, and address. I store them in an ArrayList. Now I have three different methods for letting users search for contacts by name, email, or address. Except for the comparison statements, each is identical to the others, one has name.equals(contact.getName()), another has email.equals(contact.getEmail()), and the last has address.equals(contact.getAddress()). 。 I know the DRY principle, I think it can be applied here, is there a way to avoid repeating myself in this case?

public void searchName(String name)
{
    for(int i = 0; i < contacts.size(); i++)
    {
      Contact contact = contacts.get(i);

if(name.equals(contact.getName())
       {
          printContactInfo(contact);
       }
     }
}

The other two methods are exactly the same, but instead of using a name, you use an email or address.

Solution

You can pass it as a function. The syntax enhancements of Java 8 are ideal for such use cases:

public void searchName(String name) {
    search(name, Contact::getName);
}

public void searchEmail(String email) {
    search(email, Contact::getEmail);
}

public void searchAddress(String address) {
    search(address, Contact::getAddress);
}

private void search(String s, Function<Contact, String> f) {
    contacts.stream().filter(c -> f.apply(c).equals(s)).forEach(this::printContactInfo);
}

Related Problems and Solutions