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

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

    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
    

提交回复
热议问题