如何有条件地替换集合中的值,例如replaceIf(Predicate<T>)? [英] 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?
我们总是可以做 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<>)
.
推荐答案
这只适用于 List
,不适用于 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
,使用 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");
给出相同的结果.
这篇关于如何有条件地替换集合中的值,例如replaceIf(Predicate<T>)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!