Library contents

Java String.transform

Pass a string to a function and return the result produced by that function.

A simple example

String.transform

  1. Start with "12"
  2. Do this Transform text by parsing it
  3. Result 12 as a number
The supplied function receives the string and supplies the return value.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("12".<Integer>transform(Integer::parseInt));
    }
}
Output
12

Syntax

Java syntax
public <R> R transform(Function<? super String,? extends R> f)
JDK 21 method signatures (1)
public <R> R transform(Function<? super String,? extends R> f)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Turn a room-capacity field into a number

A booking form supplies a capacity or party size before a room can be assigned. Check the value at that boundary so the booking logic can work with a usable number of places.

From the programString capacity = " 24 "
Result25
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String capacity = " 24 ";
        System.out.println(capacity.strip().transform(Integer::parseInt) + 1);
    }
}
Output
25

After parsing, adding one performs numeric addition.

Advertisements

Normalize a parcel label in one pipeline

Two terminals can enter the same short label with different capitalization or padding. Normalize the incoming spelling before lookup so the stored identifiers can follow a consistent convention.

From the programString label = " ab-17 "
ResultAB-17
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String label = " ab-17 ";
        String normalized = label.transform(s -> s.strip().toUpperCase(java.util.Locale.ROOT));
        System.out.println(normalized);
    }
}
Output
AB-17

The supplied function removes padding and uppercases the code.

Read the afternoon delivery

A store receives a quantity as text from a barcode reader. Read the whole decimal quantity and add it to the two units already at the desk. What total should the register show?

Given“18” + 2 on hand
Worked result20

What to watch for

The result may have a different type. Parsing and other supplied functions can throw their own exceptions.

Documentation for String.transform