如何在Collection中有条件地替换值,例如replaceIf(Predicate< T>)? [英] How to replace a value conditionally in a Collection, such as replaceIf(Predicate<T>)?
问题描述
如果值为null,是否有任何简单的方法可以替换列表或集合中的值?
Is there any easy way we could replace a value in a List or Collection if the value is null?
我们总是可以做 list.stream()。filter(Objects :: nonNull);
并且可能加0回到列表。
We can always do list.stream().filter(Objects::nonNull);
and maybe add 0 back to the list.
但我要找的是像 list.replaceIf(Predicate<>)
这样的API。
But what I am looking for is an API like list.replaceIf(Predicate<>)
.
推荐答案
这只适用于列表
,而不是 Collection
,因为后者没有替换或设置元素的概念。
This will only work on a List
, not on a Collection
, as the latter has no notion of replacing or setting an element.
但是给出列表
,使用 List.replaceAll()
方法很容易做到你想做的事情:
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);
输出:
[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);
}
这将按以下方式调用:
replaceIf(list, Objects::isNull, s -> "x");
给出相同的结果。
这篇关于如何在Collection中有条件地替换值,例如replaceIf(Predicate< T>)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!