Let's say I have a very simple class, Person, which contains a name and address:
public class Person {
String name;
String address;
public Person(final String name,
final String address) {
this.name = name;
this.address = address;
}
public String getName() {
return name;
}
public void setName(final String newName) {
this.name = newName;
}
public String address() {
return address;
}
public void setAddress(final String newAddress) {
this.address = newAddress;
}
}
I now have a Set containing all of the known Person objects, and I want to update the address of one of the persons based only on their name. For that I have the following:
persons.stream()
.filter(person -> personToUpdate.getName().equalsIgnoreCase(person.getName()))
.forEach(person -> {
person.setAddress(personToUpdate.getAddress());
});
However, my problem is when I have a new person altogether who is not in the Set. How do I check the Set to see if the person exists, and if so, update their address. But if they don't exist, add them to the list. I know this is simple, but for whatever reason I just cannot think how to achieve this right now. I do not want to go down the road of creating a List of all the names, comparing the new name, if they're in the list etc etc etc. I'd rather keep it as concise as possible.
EDIT: Names will be unique!