Search

Dark theme | Light theme

March 3, 2021

Java Joy: Apply Function To String With Transform

In Java 12 the transform method was add to the String class. This method accepts a Function as argument. The function must have a single parameter of type String and can return any other type. The nice thing is that it works on a String instance, so we can directly use the transform method when we have a String value. We don't have to pass the String object to another method to tranform it, but we can define the tranformation function close to the String value.

In the following example we take a String value and apply some functions with the transform method:

package mrhaki.lang;

import java.util.stream.Collectors;

public class StringTransform {
    public static void main(String[] args) {
        String alphabet = "abcdefghijklmnopqrstuvwxyz";
        
        // Find all letters that have an even
        // int representation and join the results
        // back into a string.
        String letters = alphabet
                .transform(s -> s.chars()
                                 .filter(n -> n % 2 == 0)
                                 .mapToObj(n -> String.valueOf((char) n))
                                 .collect(Collectors.joining()));

        assert "bdfhjlnprtvxz".equals(letters);

        // Transform the string to a User object.
        User user = "mrhaki,Hubert Klein Ikkink"
                .transform(name -> new User(name.split(",")[0], name.split(",")[1]));

        assert "mrhaki".equals(user.alias);
        assert "Hubert Klein Ikkink".equals(user.fullName);
    }

    /**
     * Simple class to store alias and full name.
     */
    private static class User {
        private final String alias, fullName;

        private User(final String alias, final String fullName) {
            this.alias = alias;
            this.fullName = fullName;
        }
    }
}

Written with Java 15.