。
如果值为空,有什么简单的方法可以替换列表或集合中的值吗?
我们总是可以做list.stream().filter(Objects::nonNull);
,也许可以将 0 加回列表中。
但我正在寻找的是像 list.replaceIf(Predicate<>)
这样的 API
这
只适用于List
,不适用于Collection
,因为后者没有替换或设置元素的概念。
但是给定一个List
,使用 List.replaceAll()
方法做你想做的事情很容易:
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]
如果你想要一个接受谓词的变体,你可以写一个小的帮助函数来做到这一点:
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");
给出相同的结果。
你需要一个简单的映射函数:
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
试试这个。
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);
}
和
List<String> list = Arrays.asList("a", "b", "c");
replaceIf(list, x -> x.equals("b"), "B");
System.out.println(list);
// -> [a, B, c]
这可能会尝试:
list.removeAll(Collections.singleton(null));