'How to return the key that I wrote if the key was not found

Let's say we have a HashMap named hsm, and I want the value of hsm.get(invalidKey).

Because the invalidKey has no mapping it will return for me a null value, but I want it to return for me the invalidKey.

I already know of a method where we check first if hsm.containsKey(invalidKey) to make sure it's valid and not overwriting a value in the array, but is there another method?

Solution 1:[1]

I should have used:

hsm.getOrDefault(invalidKey, invalidKey);

It searches the map using the first argument as a key. If no result is found then the second argument is returned, which in this case is the same as the key.


This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 catch23