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

前端 未结 4 1381
遥遥无期
遥遥无期 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:49

    Try this.

    public static  void replaceIf(List list, Predicate predicate, T replacement) {
        for (int i = 0; i < list.size(); ++i)
            if (predicate.test(list.get(i)))
                list.set(i, replacement);
    }
    

    and

    List list = Arrays.asList("a", "b", "c");
    replaceIf(list, x -> x.equals("b"), "B");
    System.out.println(list);
    // -> [a, B, c]
    

提交回复
热议问题