GeniusAreMade
GeniusAreMade

Reputation: 19

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?

Upvotes: 0

Views: 88

Answers (1)

GeniusAreMade
GeniusAreMade

Reputation: 19

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.

Upvotes: 1

Related Questions