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

A lambda is a small function written inline, such as s -> s.strip(). The list methods added in Java 8 accept such functions and apply them to every element. There are two families, and choosing between them is the main decision:

  • In place: replaceAll, removeIf and sort change the list itself. They need a mutable list, and every reference to that list sees the change.
  • Into a new list: stream().map(...).toList() leaves the original untouched and returns a new list, possibly of a different element type. It works on immutable lists too.

A third tool, forEach, changes nothing in the list itself; it runs an action per element, which can change the elements only if they are mutable objects.

Lambda-based list operations
MethodSinceEffectTakes
list.replaceAll(op)Java 8Replaces each element with op(element)UnaryOperator<T>
list.removeIf(test)Java 8Removes elements that pass the testPredicate<T>
list.sort(cmp)Java 8Sorts in placeComparator<T>
list.forEach(action)Java 8Runs an action per elementConsumer<T>
stream().map(f).toList()Java 8, Java 16A new list of resultsFunction<T, R>
Collectors.joining, reduceJava 8One combined valueVarious

All programs here were run with JDK 21. Simple loops over lists are compared on looping through a list.

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.

Java
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:

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
  • replaceAll(String::strip) removed the surrounding spaces from every name; the second replaceAll capitalized each one.
  • removeIf removed the names shorter than three letters, here Li.
  • sort with a comparator built from comparing(String::length) and a natural-order tie-breaker ordered the names by length.
  • forEach printed a greeting per name without changing the list.
  • All four need a mutable list: on List.of(...) they throw 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.

Java
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:

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]
  • map(i -> i.qty() + " x " + i.name()) changes the element type, from Item to String, which replaceAll cannot do.
  • A conditional inside map creates a discounted copy of the expensive items only; the bag became 21.6.
  • mapToDouble(...).sum() and Collectors.joining reduce the list to one value.
  • The last line shows the original bag at its old price: map never touched the source list.

Updating elements, mutable and immutable

Records are immutable, so updating one means replacing it. The program does that with replaceAll, with set by index, and on an immutable list, then contrasts mutable elements and composed operations.

Java
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:

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, withPrice, returns a copy with one field changed. replaceAll with a condition swaps in the updated bag and leaves the rest as they were.
  • list.set(i, list.get(i).withPrice(...)) updates one known position.
  • An immutable list cannot be changed, so stream().map(...).toList() builds the discounted version while the frozen original keeps its prices.
  • When the elements themselves are mutable, such as StringBuilder, forEach can change them in place, even in an immutable list. That is often a sign the design should use immutable values instead.
  • UnaryOperator values can be combined into one function and applied in a single pass.

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.

Java
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:

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]
The four kinds of method reference
KindExampleSame as
Static methodString::valueOfx -> String.valueOf(x)
Method of a particular objectprefix::concatx -> prefix.concat(x)
Method of the elementString::toUpperCasex -> x.toUpperCase()
ConstructorUser::newx -> new User(x)
  • Function.andThen chains functions: uppercase first, then add an exclamation mark. compose applies them in the opposite order.
  • A lambda may use local variables only if they are effectively final, never reassigned. Counting with count++ inside forEach does not compile; an array or AtomicInteger holder works, though a loop or count() is clearer.
  • 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 try, or catch inside the lambda and rethrow an unchecked exception.

Composing functions and working with indexes

The list methods take functional interfaces from java.util.function, and those interfaces have helper methods of their own. The program composes two functions both ways, uses an identity function as a default, and handles the case replaceAll cannot: a transformation that needs the element's position.

Java
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:

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]
  • f.andThen(g) applies f first and g second, so 2 became 3 and then 30. f.compose(g) applies g first: 2 became 20 and then 21.
  • UnaryOperator.identity() returns its argument unchanged, a convenient default when a transformation is optional.
  • The lambda given to replaceAll sees only the element. When the index matters, stream the indexes with IntStream.range, or fill an array with Arrays.setAll, whose lambda receives the index.
  • For numbers, the primitive interfaces such as IntUnaryOperator work on int directly. A List<Integer> boxes every value, while an int[] with Arrays.stream(...).map(...) does not.

Side effects and failures inside the lambda

The lambda passed to forEach, replaceAll or removeIf runs while the list is being walked. The program changes the list from inside such a lambda, and then lets the lambda throw part of the way through, to see what state each method leaves behind.

Java
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:

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 forEach threw ConcurrentModificationException, but only after the loop: ArrayList.forEach checks the modification count at the end, so dee had already been added. replaceAll behaves the same way. Never change the structure of a list from a lambda running over it.
  • ArrayList.removeIf 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.
  • replaceAll replaces elements one at a time, so the same exception left a half-transformed list: [10, 5, 0, 4]. Code that must be all-or-nothing should build a new list and swap it in only on success.
  • A stream with map 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.

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.

Java
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):

Output
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
  • replaceAll, the index loop, ListIterator.set 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 a LinkedList, the index loop would be the exception: every get(i) and set(i) walks the chain, while replaceAll and ListIterator.set stay linear.
  • The stream allocates a second list as well. It was sometimes slower and sometimes not; toList() knows the size in advance and fills one array, so the extra cost is small.
  • 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 toUpperCase. Measuring in a fixed order without warm-up gives misleading rankings; see the JMH page.

Choose between in-place and new-list transformation for correctness and clarity, not speed.

Which approach to use

Choosing how to change list elements
GoalUse
Transform every element, same type, list is mutablelist.replaceAll(op)
Transform into a new list, or a different typestream().map(f).toList()
Update one recordlist.set(i, old.withX(...))
Remove by conditionremoveIf
Reorderlist.sort(comparator)
Run a side effect per elementforEach
Combine into one valuejoining, sum, reduce
Steps that throw checked exceptionsA plain loop

For more stream operations, see the streams page; for filtering, filtering a list.