1

Given I am checking my hashmap as follows

String firstName = map.get(UserDetail.FIRST_NAME); String lastName = map.get(UserDetail.LAST_NAME); String age = map.get(UserDetail.AGE); double height = Double.parseDouble(map.get(UserDetail.HEIGHT) double weight = Double.parseDouble(map.get(UserDetail.WEIGHT) String email = map.get(UserDetail.EMAIL); 

How would I check that the key actually exists in my hashmap before attempting to retrieve the value. At the moment I keep getting a NullPointerException regularly.

0

1 Answer 1

2

Before Java 8, you have to explicitly do the check :

String firstName = map.get(UserDetail.FIRST_NAME); // null guard if (firstName != null){ // invoke a method on firstName } 

After Java 8, you could use the Map.getOrDefault() method.

For example :

String firstName = map.getOrDefault(UserDetail.FIRST_NAME, ""); 

Now, in some cases, having a default value is not suitable as you want to do the processing only if the value is contained in the map and that is also not null.

In this configuration, a better way to address it is using Optional combined with ifPresent() :

Optional<String> optional = Optional.of(map.get(UserDetail.FIRST_NAME)); optional.ifPresent((s)->myProcessing()); 

You could also inline Optional if it used once :

Optional.of(map.get(UserDetail.FIRST_NAME)) .ifPresent((s)->myProcessing()); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.