Java List.replaceAll
Apply a transformation to each existing element and store the transformed value in the same position.
A simple example
List.replaceAll
- Start with " A ", " B "
- Do this Trim each element
- Result "A", "B"
Syntax
labels.replaceAll(String::strip)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaClean the names on two visitor badges
A reception desk receives visitor names copied from an email. Extra spaces at the edges would make the printed badges look uneven, so the desk cleans each name while preserving arrival order.
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var names = new ArrayList<>(List.of(" Mira ", " Sam"));
names.replaceAll(String::strip);
System.out.println(String.join(", ", names));
}
}
Mira, Sam
Each label is stripped in place and the badge sequence stays the same.
Add setup time to workshop slots
A workshop coordinator adds five minutes of setup to every session. Each slot keeps its place on the timetable and receives its own updated duration.
import java.util.ArrayList;
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var minutes = new ArrayList<>(List.of(30, 45));
minutes.replaceAll(n -> n + 5);
System.out.println(minutes);
}
}
[35, 50]
The operator replaces each old duration with a duration five minutes longer.
Clean a volunteer roster
Two names pasted from a form have stray spaces. The printer trims surrounding spaces from each label. Which names remain on the badge sheet?
What to watch for
Use a list that permits replacement. If a transformation can fail partway, earlier elements may already be changed.