Conditionally replace values in a List in Java
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.Arrays; import java.util.List; class Main { public static void main(String[] args) { List<String> words = Arrays.asList("A", null, null, "B", "C", null, "D", null); words.replaceAll(s -> s != null ? s : ""); System.out.println(words); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.Arrays; import java.util.Collections; import java.util.List; class Main { public static void main(String[] args) { List<String> words = Arrays.asList("A", null, null, "B", "C", null, "D", null); Collections.replaceAll(words, null, ""); System.out.println(words); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; class Main { public static void main(String[] args) { List<String> words = Arrays.asList("A", null, null, "B", "C", null, "D", null); List<String> newList = words.stream() .map(s -> s != null ? s : "") .collect(Collectors.toList()); System.out.println(newList); } } |
Output:
[A, , , B, C, , D, ]
That’s all about conditionally replacing values in a List in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)