This post will discuss how to conditionally replace values in a List in Java.

1. Using List.replaceAll() method

A common approach to in-place replace values in the input list is using the replaceAll() method. It replaces each element of the list with the result of applying the specified operator to that element.

Here’s complete usage of this method to remove null values in the List of a string with an empty string:

Download  Run Code

Output:

[A, , , B, C, , D, ]

2. Using Collections.replaceAll() method

Before Java 8, you can use the Collections.replaceAll() method to in-place replace all instances of the supplied value in a list with another. Note that this method cannot be used to “conditionally” replace values, as it does not accept any predicate.

Download  Run Code

Output:

[A, , , B, C, , D, ]

3. Using Java Streams

If you need a new list and prevent modifications to the original list, you can do so with Java Streams. The Stream API provides the map() method that can apply a given function to each element of the input stream.

Download  Run Code

Output:

[A, , , B, C, , D, ]

That’s all about conditionally replacing values in a List in Java.