5

I have used compute method as well as merge method. However I am still not sure how merge method differs from compute methods.

I was asked a question in interview to maintain a counter of hits for given list of IP addresses. It was a basic implementation of Map where key is the IP and value is the number of hits.

I implemented it with computeIfAbsent method but that was not sufficient when the key is present so I had to change the implementation to use merge method.

Can we say that merge is equivalent to using both compute methods at same time?

Naman
  • 27,789
  • 26
  • 218
  • 353
Eager
  • 225
  • 1
  • 8

1 Answers1

4

Well yes logically it is, you could say that it is equivalent to:

merge(){
   computeIfAbsent(...)
   computeIfPresent(...)
}

but of course they have different implementations

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • 1
    A difference is that `merge` always receives the value, while `computeIf*` allows to create a new value lazily. – fps Oct 18 '18 at 20:59