Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a value conditionally in a Collection, such as replaceIf(Predicate<T>)?

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<>).

like image 826
Raghu K Nair Avatar asked Mar 04 '16 23:03

Raghu K Nair


People also ask

How to replace List values in Java?

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.

How do I change the value of a list in Java 8?

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.

How do you replace all elements in an ArrayList in Java?

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.

How do you filter data in Java?

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.


2 Answers

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.

like image 167
Stuart Marks Avatar answered Sep 21 '22 18:09

Stuart Marks


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
like image 42
Nándor Előd Fekete Avatar answered Sep 19 '22 18:09

Nándor Előd Fekete