Refactoring same loop logic with different input data I have these two methods:

public static String buildLine(String[] values) {
    StringBuilder lineBuilder = new StringBuilder();
    for (int i = 0; i &lt; values.length - 1; i++) {
        lineBuilder.append(values[i]).append(SEPARATOR);
    }
    lineBuilder.append(values[values.length - 1]);
    return lineBuilder.toString();
}

public static String buildLineFromNodeWorker(String[] values, NodeDecorator nodeWorker) {
    StringBuilder lineBuilder = new StringBuilder();
    for (int i = 0; i &lt; values.length - 1; i++) {
        lineBuilder.append(
                nodeWorker.getItemValueFromAttribute(values[i]))
                .append(SEPARATOR);
    }
    lineBuilder
            .append(nodeWorker
                    .getItemValueFromAttribute(values[values.length - 1]));
    return lineBuilder.toString();
}


they're identical except for what I'm passing to the append method from the StringBuilder.

I'm not able to find a way to write the "business logic" of the loop just once.
One way using the Template method pattern:

abstract class LineBuilder {
    protected abstract String getLine(String value);

    public String buildLine(String[] values) {
        StringBuilder lineBuilder = new StringBuilder();
        for (int i = 0; i &lt; values.length - 1; i++) {
            lineBuilder.append(getLine(values[i])).append(SEPARATOR);
        }
        lineBuilder.append(getLine(values[values.length - 1]));
        return lineBuilder.toString();
    }
}

class StringLineBuilder extends LineBuilder {
    protected String getLine(String value) {
        return value;
    }
}

class NodeWorkerLineBuilder extends LineBuilder {
    private final NodeDecorator nodeWorker;

    public NodeWorkerLineBuilder(NodeDecorator nodeWorker) {
        this.nodeWorker = nodeWorker;
    }

    protected String getLine(String value) {
        return nodeWorker.getItemValueFromAttribute(value);
    }
}


Once you define the above classes you can replace the code inside your methods with:

public static String buildLine(String[] values) {
    return new StringLineBuilder().buildLine(values);
}

public static String buildLineFromNodeWorker(String[] values,
        NodeDecorator nodeWorker) {
    return new NodeWorkerLineBuilder(nodeWorker).buildLine(values);
}