Articles

Java Program to replace a substring in a String using replace() and Lambda Expression

Share

Program to replace a substring using replace method

Simple Program:

class Main {
    public static void main(String[] args) {
            String str = "newBay", replace="new";
            String replaceTo = "programmer";


            System.out.println("Orignal string : " + str);
            System.out.println("New string : " +
                    str.replace( replace, replaceTo));


    }
}

Output:

Orignal string : newBay
New string : programmerBay

This is another way, but this time with lambda expression which was introduced in Java 8

Program to replace a substring using Lambda Expression

@FunctionalInterface
interface MyFunctionInterface
{
    String replaceMe(String to,String with );
}
class Main {
    public static void main(String[] args) {
            String str = "newBay", replace="new";
            String replaceTo = "programmer";

MyFunctionInterface i = (r,rt) -> str.replace(r,rt);
System.out.println("Original String : "+str);
System.out.println("Original String : "+i.replaceMe(replace,replaceTo));

    }
}

Output:

Orignal string : newBay
New string : programmerBay

Also read: Java program to replace a substring without using replace method

This post was last modified on July 4, 2022

Sandeep Verma

Published by
Sandeep Verma
Tags: java Lamda Expression program replace a substring