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

前端 未结 4 1374
遥遥无期
遥遥无期 2021-02-13 23:44

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::nonNu

4条回答
  •  广开言路
    2021-02-14 00:39

    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 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  void replaceIf(List list, Predicate pred, UnaryOperator 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.

提交回复
热议问题