Library contents

Java List.replaceAll

Apply a transformation to each existing element and store the transformed value in the same position.

A simple example

List.replaceAll

  1. Start with " A ", " B "
  2. Do this Trim each element
  3. Result "A", "B"
Applying the same text operation to each element preserves the list order.

Syntax

Java syntax
labels.replaceAll(String::strip)
Run these examples in Java

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

java Main.java

Clean 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.

ResultMira, Sam
Main.java
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));
    }
}
Output
Mira, Sam

Each label is stripped in place and the badge sequence stays the same.

Advertisements

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.

Result[35, 50]
Main.java
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);
    }
}
Output
[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?

Given“ Isa” · “Lou ”
Worked resultIsa · Lou

What to watch for

Use a list that permits replacement. If a transformation can fail partway, earlier elements may already be changed.

Documentation for List.replaceAll