Why does Map.compute() take a BiFunction

前端 未结 1 1745
醉梦人生
醉梦人生 2021-02-14 07:30

I don\'t understand why Map.compute() and Map.computeIfPresent() take BiFunction parameters as well as Map.computeIfAbsent()

1条回答
  •  孤城傲影
    2021-02-14 08:17

    You may see computeIfPresent as the single-entry pendant of replaceAll whereas the latter requires the key as a parameter, but it’s natural to support the same function as input to both operations and the API is consistent here: it always provides the key as parameter to the function.

    Generally, providing the key raises the reusability of existing functions, be it method references or ordinary class implementations (i.e. non-lambda) of the BiFunction interface. But this reusability may also affect the performance of lambda expressions given the existing JRE implementation:

    As described here, lambda expressions capturing values from the surrounding context may end up in individual instances for each capturing process, whereas lambda expressions only using their parameters (non-capturing lambdas) will end up as a singleton instance. In contrast, having an otherwise unused parameter has no performance impact. So receiving the key as a parameter is preferable for that reason as well.

    0 讨论(0)
提交回复
热议问题