Learn how to replace a string with another string in Java 8 using Stream API and the replace() method with an example.
Code Explanation (Step-by-Step)
• Stream.of() creates a stream from the string.
• map() replaces “is” with “was” using the replace() method.
• forEach() prints the modified string .
• Final output is “Your technology was Java”.
import java.util.stream.Stream;
public class ReplaceTest {
public static void main(String[] args) {
String s1 = "Your technology is Java";
Stream.of(s1)
.map(r -> r.replace("is", "was"))
.forEach(System.out::println);
}
}
Output :-
Your technology was Java
How String Replacement Works in Java
public class ReplaceTest {
public static void main(String[] args) {
String str = "Your technology is Java";
String result = str.replace("is", "was");
System.out.println(result);
}
}
Output :-
Your technology was Java
FAQ
Does replace() modify the original string?
No. Strings are immutable in Java. It returns a new string.
Can replace() replace multiple occurrences?
Yes, all matching occurrences are replaced.
What is the difference between replace() and replaceAll()?
replace() replaces literal text, whereas replaceAll() uses regular expressions.
How do you replace a string in Java 8?
Use the replace() method:
str.replace("old", "new");