How to replace a value conditionally in a collection, for example replaceIf (Predicate <T>)?

Is it possible to easily replace a value in a list or collection if the value is null?

We can always do list.stream().filter(Objects::nonNull); and possibly add 0 back to the list.

But I'm looking for an API like list.replaceIf(Predicate<>) .

+6
source share
4 answers

This will only work on List , not Collection , since the latter has no idea about replacing or setting an element.

But given List 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 variant that accepts a predicate, you can write a small helper function to do this:

 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 will be called as follows:

 replaceIf(list, Objects::isNull, s -> "x"); 

giving the same result.

+12
source

You need a simple display 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 
+2
source

Try it.

 public static <T> void replaceIf(List<T> list, Predicate<T> predicate, T replacement) { for (int i = 0; i < list.size(); ++i) if (predicate.test(list.get(i))) list.set(i, replacement); } 

and

 List<String> list = Arrays.asList("a", "b", "c"); replaceIf(list, x -> x.equals("b"), "B"); System.out.println(list); // -> [a, B, c] 
+2
source

This may try the following:

 list.removeAll(Collections.singleton(null)); 
0
source

All Articles