# Updating persons in database with newly created addresses [closed]

I have the following code, and I'd like to refactor it to a more functional way:

public void processPersons(List<Person> personList) {
for (Person person : personList) {
}
}
}


How do I convert the above to a more functional style of programming?

• Use method references to shorten your map() Jul 20, 2017 at 9:11
• Why is this off-topic? Jul 21, 2017 at 3:41
• Well, I can remove that part, and say: "how can I refactor this code into functional code?". The code is working in my example, that's the first part of the code. The second part is there to show that I tried something, and didn't just put some code here for others to refactor. I had a similar question on SO, and they pointed me to CodeReview. It's quite ironic that now you point me back. Jul 22, 2017 at 4:49
• @JudeNiroshan That seems to have been an attempt at refactoring the code, but the attempt failed. That doesn't make the original code non-working or off-topic. Jul 22, 2017 at 9:13
• You can probably rewrite your code like this personList.forEach(person -> Optional.ofNullable(createAddress(person)).ifPresent(addressId -> updateDbStatus(addressId, person))); , but I wouldn't recommend it. The code you have now is better in my opinion. Jul 22, 2017 at 9:16

One of variants is to have PersonWithAddress subclass with created addressIp:

    persons
.stream()
.forEach(this::updateDbStatus);


You call updateDbStatus where check the address for null:

void updateDbStatus(PersonWithAddress personWithAddress) {
// do the update
}
}


Model classes like these ones:

class Person{
Person(final Person original) {
// copy constructor
}
}

super(person);
}

}

// have a logic to create an address
return 0;
}
}

• Thanks for that. I had something similar (I just used a Pair/Tuple2), but I didn't think the end result was better than the code already in place. Jul 21, 2017 at 3:43
• @ErikPragt That might be an indication that the code you currently have isn't that bad after all. Jul 22, 2017 at 9:11
• @ErikPragt this answer is most helpful, so flag it. beside that we can't see your answer yet! Aug 1, 2017 at 5:34

As you are working with Java 8, you'd be happy to explore the other features in it like Optional<T>

You can change your createAddress() to return an Optional which will be more expressive.

Optional<Person> createAddress(person){
//write your logic and return the result wrapped in an Optional
}


As addressId has one-to-one mapping with Person, you should add an identifier to the Person class to hold the addressId. Then you have to modify the method signature of updateDbStatus as updateDbStatus(Person person)

class SomeClass{

void someMethod(){

personList.stream()