Spring Boot methods to add and remove relationships I have a Spring Boot application and I wrote a piece of code to manage relationships between two entities.

The code consists mostly in these two methods:

@Override
    public void associateDocumentsToPersonRecord(Long personRecordId, AssociationDTO associationDTO) {
        PersonRecord personRecord = personRecordRepository.findById(personRecordId).orElse(null);
        if (personRecord == null)
            return;

        for (Long documentId : associationDTO.getDocumentsId())
            documentRepository
                    .findById(documentId)
                    .ifPresent(document -&gt; personRecord.getDocuments().add(document));

        personRecordRepository.save(personRecord);
    }

    @Override
    public void removeAssociateDocumentsToPersonRecord(Long personRecordId, AssociationDTO associationDTO) {
        PersonRecord personRecord = personRecordRepository.findById(personRecordId).orElse(null);
        if (personRecord == null)
            return;

        for (Long documentId : associationDTO.getDocumentsId())
            documentRepository
                    .findById(documentId)
                    .ifPresent(document -&gt; personRecord.getDocuments().remove(document));

        personRecordRepository.save(personRecord);
    }


One method is for adding relations, the other is to remove them.

I definitely get the smell of duplicated code and the only thing that changes is remove or add between the two methods.
How could I refactor this code in the most elegant way?
You may extract the action part as a method parameter (I am using BiConsumer in this case).

@Override
public void performActionOnRecords(Long personRecordId, AssociationDTO associationDTO, BiConsumer&lt;PersonRecord,Document&gt; action) {
    PersonRecord personRecord = personRecordRepository.findById(personRecordId).orElse(null);
    if (personRecord == null)
        return;

    for (Long documentId : associationDTO.getDocumentsId())
        documentRepository
                .findById(documentId)
                .ifPresent(document -&gt; action.accept(personRecord,document));

    personRecordRepository.save(personRecord);
}


and call the methods as  

performActionOnRecords(personId, associationDTO, (personRecord, document) -&gt; personRecord.getDocuments().add(document)); // To add document


and,

performActionOnRecords(personId, associationDTO, (personRecord, document) -&gt; personRecord.getDocuments().remove(document)); // To remove document