Is there any easy way we could replace a value in a List or Collection if the value is null?
We can always do list.stream().filter(Objects::nonNull);
and maybe add 0 back to the list.
But what I am looking for is an API like list.replaceIf(Predicate<>)
.
You can replace an element of an ArrayList using the set() method of the Collections class. This method accepts two parameters an integer parameter indicating the index of the element to be replaced and an element to replace with.
To update or set an element or object at a given index of Java ArrayList, use ArrayList. set() method. ArrayList. set(index, element) method updates the element of ArrayList at specified index with given element.
In order to replace all elements of ArrayList with Java Collections, we use the Collections. fill() method. The static void fill(List list, Object element) method replaces all elements in the list with the specified element in the argument.
Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.
This will only work on a List
, not on a Collection
, as the latter has no notion of replacing or setting an element.
But given a List
, it's pretty easy to do what you want using the List.replaceAll()
method:
List<String> list = Arrays.asList("a", "b", null, "c", "d", null);
list.replaceAll(s -> s == null ? "x" : s);
System.out.println(list);
Output:
[a, b, x, c, d, x]
If you want a variation that takes a predicate, you could write a little helper function to do that:
static <T> void replaceIf(List<T> list, Predicate<? super T> pred, UnaryOperator<T> op) {
list.replaceAll(t -> pred.test(t) ? op.apply(t) : t);
}
This would be invoked as follows:
replaceIf(list, Objects::isNull, s -> "x");
giving the same result.
You need a simple map function:
Arrays.asList( new Integer[] {1, 2, 3, 4, null, 5} )
.stream()
.map(i -> i != null ? i : 0)
.forEach(System.out::println); //will print: 1 2 3 4 0 5, each on a new line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With