Java String.transform
Pass a string to a function and return the result produced by that function.
A simple example
String.transform
- Start with "12"
- Do this Transform text by parsing it
- Result 12 as a number
class Main {
public static void main(String[] args) throws Exception {
System.out.println("12".<Integer>transform(Integer::parseInt));
}
}
12
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.javaTurn 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.
class Main {
public static void main(String[] args) throws Exception {
String capacity = " 24 ";
System.out.println(capacity.strip().transform(Integer::parseInt) + 1);
}
}
25
After parsing, adding one performs numeric addition.
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.
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);
}
}
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?
What to watch for
The result may have a different type. Parsing and other supplied functions can throw their own exceptions.