'Replace a String with specific list of strings in java

Here is the example,

public class Demo{

    public static void main (String args[]) {

        List<String> varList = Arrays.asList("VAR_TEMP", "VAR_TEMPA", "VAR_TEMPB");
        String operation = "var temp = VAR_TEMPB";

        for (String var : varList) {
            operation = (operation.contains(var))
                    ? operation.replace(var, "'HI'")
                            : operation;
        }

        System.out.println("Final operation : " + operation);
    }
}

I am trying to replace the Operation string with list of strings.

I am expecting the response for the above code is like,

Final operation : var temp = HI

But it is giving the response like below,

Final operation : var temp = 'HI'B

While iterating the list of String it is taking the first matching("VAR_TEMP") instead of taking the exact match("VAR_TEMPB"). Can you please suggest the way to achieve this the expected response.



Sources

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

Source: Stack Overflow

Solution Source