Map.computeIfAbsent: Write a clear and concise code

How?

Suppose you are solving a graph problem where you have been given a 2D array of edges and you need to find the shortest path between a source and a destination node. At this point, you could create a graph from the given edges.

or you can write the same code using Map.computeIfAbsent method

Cool??

Method Signature

Behaviour

  • First, it checks if the key is present in the map. If the key is present, and a non-null value is related to the key, then it returns that value.
  • If the key isn’t present in the map, or the null value is related to the key, then it attempts to compute the value using the given mappingFunction. It also enters the calculated value into the map unless the calculated value is null.
  • If the mappingFunction returns null, the map records no mapping
  • If the mappingFunction throws an unchecked exception, then the exception is re-thrown, and the map records no mapping

Test Your Knowledge

Seems like you got it, okay, so what would happen if try to do something like this (not sure why would you do it):

Hint: NPE

References

Rate this post

Leave a Reply