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

僤鯓⒐⒋嵵緔 提交于 2019-12-22 04:09:42

问题


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


回答1:


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.




回答2:


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



回答3:


Try this.

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]



回答4:


This may try this:

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


来源:https://stackoverflow.com/questions/35807818/how-to-replace-a-value-conditionally-in-a-collection-such-as-replaceifpredicat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!