Java - Using String transfrom() Examples

This tutorial shows you how to use transform() method of String in Java 12 or above.

String transfrom() is an instance method introduced in Java 12. It allows a function to be applied to a String. The function accepts a parameter of type String, while the output can be any type.

Using String transfrom()

This is the method which requires a parameter of type Function.

  public <R> R transform(Function<? super String, ? extends R> f)

In the first example, we are going to split the string into an array of strings.

  String text = "Woolha,dot,com";

  List<String> result = text.transform(t -> {
    return Arrays.asList(t.split(","));
  });

  System.out.println(result);

Output:

  [Woolha, dot, com]

 

In the second example, based on the value of the string, we are going to return another string.

  String text = "Woolha.com";

  String result = text.transform(t -> {
    if (text.contains(".com")) {
      return "A .com domain";
    } else {
      return "Not a .com domain";
    }
  });

  System.out.println(result);

Output:

  A .com domain

 

Other than the above examples, you can use transform() for a lot of other things. You can also create a function to be reused multiple times as the argument of transform(). Just make sure to not apply transfrom() on a null string to avoid NullPointerException.