'Reuse a method with nested for-loops that only differs by some lines inside the inner loop

I have a java method that basically looks like this:

public static Map<String, List<MyObject>> myMappingMethod(List<A> listOfA, List<B> listOfB) {
    final Map<String, List<MyObject>> results = new HashMap<>();
    
    for (A objA : listOfA) {
        if (!objA.meetsSomeCriteria()) {
            continue;
        }

        for (B objB : listOfB) {
            if (!objB.meetsSomeCriteria()) {
                continue;
            }
            
            createFileWithIntermediateResultsFrom(objA, objB);   // <-- seldomly needed

            // create new List<MyObject> from objA and objB and add to results
        }
    }
    
    return results;
}

Now I want to basically duplicate this method and leave out the the createFileWithIntermediateResultsFrom(objA, objB); part cause usually I don't need that (but can't take it out, cause it is needed for like 1 %).

How to avoid copy&paste with one line deletion and also avoid introducing some kind of "debug"-parameter?

(If possible, I don't want to change the signature to myMappingMethod(List<A> listOfA, List<B> listOfB, boolean createDbgFile))



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source