Change List Items with Lambdas
Lambdas let you say what should happen to each element of a list and leave the looping to the library. The same change can be applied in place, with replaceAll, removeIf and sort, or into a new list, with stream map. This page explains the difference, updates immutable records, covers the four kinds of method reference and composition, and shows the rules lambdas impose.
Contents
In place or into a new list Changing a list in place Building a new list with map Updating elements, mutable and immutable Method references and lambda rules Composing functions and working with indexes Side effects and failures inside the lambda How fast is each way of transforming? Which approach to use
In place or into a new list
A lambda is a small function written inline, such as s -> s.strip()
- In place:
,replaceAll andremoveIf change the list itself. They need a mutable list, and every reference to that list sees the change.sort - Into a new list:
leaves the original untouched and returns a new list, possibly of a different element type. It works on immutable lists too.stream().map(...).toList()
A third tool, forEach
| Method | Since | Effect | Takes |
|---|---|---|---|
list.replaceAll(op) | Java 8 | Replaces each element with op(element) | UnaryOperator<T> |
list.removeIf(test) | Java 8 | Removes elements that pass the test | Predicate<T> |
list.sort(cmp) | Java 8 | Sorts in place | Comparator<T> |
list.forEach(action) | Java 8 | Runs an action per element | Consumer<T> |
stream().map(f).toList() | Java 8, Java 16 | A new list of results | Function<T, R> |
Collectors.joiningreduce | Java 8 | One combined value | Various |
All programs here were run with JDK 21. Simple loops over lists are compared on
Changing a list in place
A list of names typed by users, with stray spaces, mixed case and one name too short to keep, is cleaned up step by step.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class InPlace {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of(" maria ", "JOHN", "li", " ahmed"));
// replaceAll: apply a function to every element, in place
names.replaceAll(String::strip);
System.out.println("stripped: " + names);
names.replaceAll(n -> n.substring(0, 1).toUpperCase() + n.substring(1).toLowerCase());
System.out.println("capitalized: " + names);
// removeIf: drop elements that match
names.removeIf(n -> n.length() < 3);
System.out.println("removeIf: " + names);
// sort with a comparator built from lambdas
names.sort(Comparator.comparing(String::length).thenComparing(Comparator.naturalOrder()));
System.out.println("sorted: " + names);
// forEach: an action per element; does not change the list
names.forEach(n -> System.out.println("hello, " + n));
}
}
Output:
stripped: [maria, JOHN, li, ahmed]
capitalized: [Maria, John, Li, Ahmed]
removeIf: [Maria, John, Ahmed]
sorted: [John, Ahmed, Maria]
hello, John
hello, Ahmed
hello, Maria
removed the surrounding spaces from every name; the secondreplaceAll(String::strip) capitalized each one.replaceAll removed the names shorter than three letters, hereremoveIf .Li with a comparator built fromsort and a natural-order tie-breaker ordered the names by length.comparing(String::length) printed a greeting per name without changing the list.forEach- All four need a mutable list: on
they throwList.of(...) .UnsupportedOperationException
Building a new list with map
A shopping cart of records is turned into labels, a discounted copy, a total and a CSV line, while the original cart stays unchanged.
import java.util.List;
import java.util.stream.Collectors;
public class IntoNewList {
record Item(String name, double price, int qty) {
}
public static void main(String[] args) {
List<Item> cart = List.of(
new Item("pen", 1.20, 10),
new Item("notebook", 3.50, 2),
new Item("bag", 24.00, 1));
// map: transform each element into something else
List<String> labels = cart.stream()
.map(i -> i.qty() + " x " + i.name())
.toList();
System.out.println("labels: " + labels);
// Records are immutable: "change" one by building a new one
List<Item> discounted = cart.stream()
.map(i -> i.price() > 10 ? new Item(i.name(), i.price() * 0.9, i.qty()) : i)
.toList();
System.out.println("bag now: " + discounted.get(2).price());
// Reduce the list to a single value
double total = cart.stream().mapToDouble(i -> i.price() * i.qty()).sum();
System.out.printf("total: %.2f%n", total);
// Join into one string
String csv = cart.stream().map(Item::name).collect(Collectors.joining(","));
System.out.println("csv: " + csv);
// The original list is unchanged by all of the above
System.out.println("original: " + cart.get(2));
}
}
Output:
labels: [10 x pen, 2 x notebook, 1 x bag]
bag now: 21.6
total: 43.00
csv: pen,notebook,bag
original: Item[name=bag, price=24.0, qty=1]
changes the element type, frommap(i -> i.qty() + " x " + i.name()) toItem , whichString cannot do.replaceAll- A conditional inside
creates a discounted copy of the expensive items only; the bag became 21.6.map andmapToDouble(...).sum() reduce the list to one value.Collectors.joining- The last line shows the original bag at its old price:
never touched the source list.map
Updating elements, mutable and immutable
Records are immutable, so updating one means replacing it. The program does that with replaceAllset
import java.util.ArrayList;
import java.util.List;
import java.util.function.UnaryOperator;
public class UpdateElements {
record Item(String name, double price, int qty) {
Item withPrice(double newPrice) {
return new Item(name, newPrice, qty);
}
}
public static void main(String[] args) {
List<Item> cart = new ArrayList<>(List.of(new Item("pen", 1.5, 10),
new Item("bag", 24.0, 1), new Item("ink", 3.0, 2)));
// Records are immutable: "changing" one means replacing it in the list
cart.replaceAll(i -> i.name().equals("bag") ? i.withPrice(19.99) : i);
System.out.println("replaced bag: " + cart.get(1));
// Update one element by index
int idx = 2;
cart.set(idx, cart.get(idx).withPrice(cart.get(idx).price() * 2));
System.out.println("doubled ink: " + cart.get(2));
// An immutable list: build a new list with the change
List<Item> frozen = List.copyOf(cart);
List<Item> discounted = frozen.stream()
.map(i -> i.qty() >= 10 ? i.withPrice(i.price() * 0.9) : i)
.toList();
System.out.println("discounted pen: " + discounted.get(0).price()
+ ", frozen pen still " + frozen.get(0).price());
// Mutable objects can be changed in place with forEach
List<StringBuilder> notes = List.of(new StringBuilder("a"), new StringBuilder("b"));
notes.forEach(sb -> sb.append("!"));
System.out.println("mutable elements via forEach: " + notes);
// Compose operations as UnaryOperators and apply them in one pass
UnaryOperator<String> trim = String::strip;
UnaryOperator<String> lower = String::toLowerCase;
List<String> tags = new ArrayList<>(List.of(" Java ", "SQL", " Go"));
tags.replaceAll(s -> lower.apply(trim.apply(s)));
System.out.println("composed: " + tags);
}
}
Output:
replaced bag: Item[name=bag, price=19.99, qty=1]
doubled ink: Item[name=ink, price=6.0, qty=2]
discounted pen: 1.35, frozen pen still 1.5
mutable elements via forEach: [a!, b!]
composed: [java, sql, go]
- A small copy method,
, returns a copy with one field changed.withPrice with a condition swaps in the updated bag and leaves the rest as they were.replaceAll updates one known position.list.set(i, list.get(i).withPrice(...))- An immutable list cannot be changed, so
builds the discounted version while the frozen original keeps its prices.stream().map(...).toList() - When the elements themselves are mutable, such as
,StringBuilder can change them in place, even in an immutable list. That is often a sign the design should use immutable values instead.forEach values can be combined into one function and applied in a single pass.UnaryOperator
Method references and lambda rules
Method references are a shorter way to write lambdas that just call one method. The program shows each kind, composes functions, and then runs into the two restrictions lambdas have.
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class LambdaRules {
record User(String name) {
static User of(String n) {
return new User(n);
}
}
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("ann", "bob"));
// Four kinds of method reference
System.out.println("static: " + names.stream().map(String::valueOf).toList());
String prefix = "user-";
System.out.println("bound: " + names.stream().map(prefix::concat).toList());
System.out.println("unbound: " + names.stream().map(String::toUpperCase).toList());
System.out.println("constructor: " + names.stream().map(User::new).toList());
System.out.println("factory: " + names.stream().map(User::of).toList());
// Composing functions with andThen / compose
Function<String, String> upper = String::toUpperCase;
Function<String, Integer> length = String::length;
System.out.println("andThen: " + names.stream().map(upper.andThen(s -> s + "!"))
.toList() + ", lengths " + names.stream().map(length).toList());
// Captured locals must be effectively final; this would not compile:
// int count = 0; names.forEach(n -> count++);
int[] count = {0};
names.forEach(n -> count[0]++);
System.out.println("counted with an array holder: " + count[0]);
// Checked exceptions cannot escape a lambda: wrap them
List<Integer> parsed = new ArrayList<>();
for (String s : List.of("1", "x", "3")) {
try {
parsed.add(parse(s));
} catch (Exception e) {
System.out.println("skipped '" + s + "': " + e.getMessage());
}
}
System.out.println("parsed: " + parsed);
System.out.println("in a lambda: " + List.of("4", "5").stream().map(s -> {
try {
return parse(s);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}).toList());
}
// Declares a checked exception
static int parse(String s) throws Exception {
if (!s.chars().allMatch(Character::isDigit)) {
throw new Exception("not a number");
}
return Integer.parseInt(s);
}
}
Output:
static: [ann, bob]
bound: [user-ann, user-bob]
unbound: [ANN, BOB]
constructor: [User[name=ann], User[name=bob]]
factory: [User[name=ann], User[name=bob]]
andThen: [ANN!, BOB!], lengths [3, 3]
counted with an array holder: 2
skipped 'x': not a number
parsed: [1, 3]
in a lambda: [4, 5]
| Kind | Example | Same as |
|---|---|---|
| Static method | String::valueOf | x -> String.valueOf(x) |
| Method of a particular object | prefix::concat | x -> prefix.concat(x) |
| Method of the element | String::toUpperCase | x -> x.toUpperCase() |
| Constructor | User::new | x -> new User(x) |
chains functions: uppercase first, then add an exclamation mark.Function.andThen applies them in the opposite order.compose- A lambda may use local variables only if they are effectively final, never reassigned. Counting with
insidecount++ does not compile; an array orforEach holder works, though a loop orAtomicInteger is clearer.count() - The functional interfaces used by lists and streams do not declare checked exceptions, so a method that throws one cannot be passed directly. Either use a loop with
, or catch inside the lambda and rethrow an unchecked exception.try
Composing functions and working with indexes
The list methods take functional interfaces from java.util.functionreplaceAll
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.IntUnaryOperator;
import java.util.function.UnaryOperator;
import java.util.stream.IntStream;
public class FunctionTypes {
public static void main(String[] args) {
// andThen runs left to right, compose right to left
Function<Integer, Integer> plus1 = x -> x + 1;
Function<Integer, Integer> times10 = x -> x * 10;
System.out.println("plus1.andThen(times10)(2) = " + plus1.andThen(times10).apply(2));
System.out.println("plus1.compose(times10)(2) = " + plus1.compose(times10).apply(2));
// UnaryOperator.identity() as a "no change" default
boolean shout = false;
UnaryOperator<String> step = shout ? String::toUpperCase : UnaryOperator.identity();
List<String> words = new ArrayList<>(List.of("a", "b"));
words.replaceAll(step);
System.out.println("identity leaves the list as it was: " + words);
// Using the index: replaceAll cannot see it, but IntStream and Arrays.setAll can
List<String> labels = new ArrayList<>(List.of("pen", "ink", "pad"));
List<String> numbered = IntStream.range(0, labels.size())
.mapToObj(i -> (i + 1) + ". " + labels.get(i)).toList();
System.out.println("numbered: " + numbered);
int[] squares = new int[6];
Arrays.setAll(squares, i -> i * i);
System.out.println("Arrays.setAll: " + Arrays.toString(squares));
// Primitive specializations avoid boxing for numeric work
IntUnaryOperator twice = x -> x * 2;
int[] doubled = Arrays.stream(squares).map(twice).toArray();
System.out.println("IntUnaryOperator on int[]: " + Arrays.toString(doubled));
}
}
Output:
plus1.andThen(times10)(2) = 30
plus1.compose(times10)(2) = 21
identity leaves the list as it was: [a, b]
numbered: [1. pen, 2. ink, 3. pad]
Arrays.setAll: [0, 1, 4, 9, 16, 25]
IntUnaryOperator on int[]: [0, 2, 8, 18, 32, 50]
appliesf.andThen(g) first andf second, so 2 became 3 and then 30.g appliesf.compose(g) first: 2 became 20 and then 21.g returns its argument unchanged, a convenient default when a transformation is optional.UnaryOperator.identity()- The lambda given to
sees only the element. When the index matters, stream the indexes withreplaceAll , or fill an array withIntStream.range , whose lambda receives the index.Arrays.setAll - For numbers, the primitive interfaces such as
work onIntUnaryOperator directly. Aint boxes every value, while anList<Integer> withint[] does not.Arrays.stream(...).map(...)
Side effects and failures inside the lambda
The lambda passed to forEachreplaceAllremoveIf
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;
public class LambdaSideEffects {
public static void main(String[] args) {
// Changing the list from inside its own forEach
List<String> names = new ArrayList<>(List.of("ann", "bob", "cy"));
try {
names.forEach(n -> {
if (n.equals("bob")) {
names.add("dee");
}
});
} catch (ConcurrentModificationException e) {
System.out.println("add inside forEach: ConcurrentModificationException, list now "
+ names);
}
// replaceAll that changes the list structure also fails
List<String> more = new ArrayList<>(List.of("x", "y"));
try {
more.replaceAll(s -> {
more.add("z");
return s.toUpperCase();
});
} catch (ConcurrentModificationException e) {
System.out.println("add inside replaceAll: ConcurrentModificationException");
}
// removeIf on ArrayList decides first, removes after: an exception changes nothing
List<Integer> nums = new ArrayList<>(List.of(1, 2, 0, 4));
try {
nums.removeIf(n -> 10 / n > 4); // divides by zero at the third element
} catch (ArithmeticException e) {
System.out.println("removeIf threw " + e.getMessage() + ", list unchanged: " + nums);
}
// replaceAll applies elements one by one: an exception leaves a half-changed list
List<Integer> half = new ArrayList<>(List.of(1, 2, 0, 4));
try {
half.replaceAll(n -> 10 / n);
} catch (ArithmeticException e) {
System.out.println("replaceAll threw " + e.getMessage() + ", list now: " + half);
}
// A stream builds a new list, so a failure leaves the source intact
List<Integer> source = List.of(1, 2, 0, 4);
try {
System.out.println(source.stream().map(n -> 10 / n).toList());
} catch (ArithmeticException e) {
System.out.println("stream map threw, source still: " + source);
}
}
}
Output:
add inside forEach: ConcurrentModificationException, list now [ann, bob, cy, dee]
add inside replaceAll: ConcurrentModificationException
removeIf threw / by zero, list unchanged: [1, 2, 0, 4]
replaceAll threw / by zero, list now: [10, 5, 0, 4]
stream map threw, source still: [1, 2, 0, 4]
- Adding to the list inside its own
threwforEach , but only after the loop:ConcurrentModificationException checks the modification count at the end, soArrayList.forEach had already been added.dee behaves the same way. Never change the structure of a list from a lambda running over it.replaceAll works in two passes: it first tests every element, then removes the marked ones. When the predicate threw on the 0, nothing had been removed yet, so the list was unchanged.ArrayList.removeIf replaces elements one at a time, so the same exception left a half-transformed list:replaceAll . Code that must be all-or-nothing should build a new list and swap it in only on success.[10, 5, 0, 4]- A stream with
never touches its source, so the failure left the original list intact. That is another reason to prefer building a new list when the transformation can fail.map
How fast is each way of transforming?
The program uppercases a million strings five ways. Each approach runs on a fresh copy, three times, and the whole series runs twice so that the second round is measured after JIT warm-up; the table shows that second round.
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.function.Consumer;
public class TransformSpeed {
static boolean print;
public static void main(String[] args) {
List<String> base = new ArrayList<>();
for (int i = 0; i < 1000000; i++) {
base.add("item-" + i);
}
System.out.printf("uppercase %,d strings (second of two rounds, after warm-up)%n",
base.size());
for (int round = 0; round < 2; round++) {
print = round == 1;
time("replaceAll(String::toUpperCase)", base, l -> l.replaceAll(String::toUpperCase));
time("index loop with set", base, l -> {
for (int i = 0; i < l.size(); i++) {
l.set(i, l.get(i).toUpperCase());
}
});
time("ListIterator.set", base, l -> {
for (ListIterator<String> it = l.listIterator(); it.hasNext(); ) {
it.set(it.next().toUpperCase());
}
});
time("stream map into new list", base, l -> {
List<String> out = l.stream().map(String::toUpperCase).toList();
if (out.size() != l.size()) {
throw new AssertionError();
}
});
time("parallel stream map", base, l -> {
List<String> out = l.parallelStream().map(String::toUpperCase).toList();
if (out.size() != l.size()) {
throw new AssertionError();
}
});
}
}
// Best of 3 runs, each on a fresh copy
static void time(String name, List<String> base, Consumer<List<String>> op) {
long best = Long.MAX_VALUE;
for (int run = 0; run < 3; run++) {
List<String> copy = new ArrayList<>(base);
long t0 = System.nanoTime();
op.accept(copy);
best = Math.min(best, System.nanoTime() - t0);
}
if (print) {
System.out.printf(" %-34s %6.1f ms%n", name, best / 1e6);
}
}
}
Output (second round only; 2 CPUs, Linux, JDK 21; approximate):
uppercase 1,000,000 strings (second of two rounds, after warm-up)
replaceAll(String::toUpperCase) 34.8 ms
index loop with set 105.2 ms
ListIterator.set 23.3 ms
stream map into new list 60.4 ms
parallel stream map 67.8 ms
, the index loop,replaceAll and the stream were all within a few times of each other on this busy shared machine, and their order changed from run to run. Almost all of the time goes into creating the million new uppercase strings, not into the way the list is walked. On aListIterator.set , the index loop would be the exception: everyLinkedList andget(i) walks the chain, whileset(i) andreplaceAll stay linear.ListIterator.set- The stream allocates a second list as well. It was sometimes slower and sometimes not;
knows the size in advance and fills one array, so the extra cost is small.toList() - The parallel stream was slower on two CPUs: the work per element is small, and splitting and merging the result cost more than they saved. With more cores, or with heavier work per element such as parsing dates or formatting text, the balance can tip the other way, so measure on the target machine before choosing a parallel stream.
- Without the warm-up round, the first approach measured looked several times slower than the others, because it paid for compiling
. Measuring in a fixed order without warm-up gives misleading rankings; see thetoUpperCaseJMH page .
Choose between in-place and new-list transformation for correctness and clarity, not speed.
Which approach to use
| Goal | Use |
|---|---|
| Transform every element, same type, list is mutable | list.replaceAll(op) |
| Transform into a new list, or a different type | stream().map(f).toList() |
| Update one record | list.set(i, old.withX(...)) |
| Remove by condition | removeIf |
| Reorder | list.sort(comparator) |
| Run a side effect per element | forEach |
| Combine into one value | joiningsumreduce |
| Steps that throw checked exceptions | A plain loop |
For more stream operations, see the