Replace match with items in order

I have a string in Java which contains a number of patterns. There is an array of values which needs to be substituted for each of this pattern in the string based on the order. Below is a sample of what the method should do.

public static String replaceValues(String withPattern, String... params){
    Matcher matcher = Pattern.compile("\{\}").matcher(withPattern);
    StringBuffer sb = new StringBuffer();
    int index =0;
    while (matcher.find()) {
        if (args.length == index) {
            matcher.appendTail(sb);
            return sb.toString();
        }
        matcher.appendReplacement(sb, params[index]);
        index++;
    }
    return sb.toString();
}
// A quick brown fox jumps over the lazy dog.
replaceValues("A quick brown {} jumps over the lazy {}", "fox", "dog"); 

This works. I just want to know if there is a more efficient way of writing this code rather than being too declarative.

Answer

You can use String#replaceFirst repeatedly to replace consecutively each param one by one.

public static String replaceValues(String withPattern, String... params){
    String string = withPattern;
    for (String param: params) {
        string = string.replaceFirst("\{}", param);
    }
    return string;
}

Since and you can achieve the same using the Stream#reduce method with the withPattern as the T identity.

public static String replaceValues(String withPattern, String... params){
    return Arrays.stream(params).reduce(
            withPattern, 
            (pattern, param) -> pattern.replaceFirst("\{}", param));
}

Leave a Reply

Your email address will not be published. Required fields are marked *