24. Transforming strings

Let's assume that we have a string and we want to transform it into another string (for example, transform it into upper case). We can do this by applying a function such as Function<? super String,​ ? extends R>.

In JDK 8, we can accomplish this via map(), as shown in the following two simple examples:

// hello world
String resultMap = Stream.of("hello")
.map(s -> s + " world")
.findFirst()
.get();

// GOOOOOOOOOOOOOOOOL! GOOOOOOOOOOOOOOOOL!
String resultMap = Stream.of("gooool! ")
.map(String::toUpperCase)
.map(s -> s.repeat(2))
.map(s -> s.replaceAll("O", "OOOO"))
.findFirst()
.get();

Starting with JDK 12, we can rely on a new method named transform​(Function<? super String, ​? extends R> f). Let's rewrite the preceding snippets of code via transform():

// hello world
String result = "hello".transform(s -> s + " world");

// GOOOOOOOOOOOOOOOOL! GOOOOOOOOOOOOOOOOL!
String result = "gooool! ".transform(String::toUpperCase)
.transform(s -> s.repeat(2))
.transform(s -> s.replaceAll("O", "OOOO"));

While map() is more general, transform() is dedicated to applying a function to a string and returns the resulting string.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset