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.

shmosel
  • 49,289
  • 6
  • 73
  • 138
methuselah
  • 12,766
  • 47
  • 165
  • 315

1 Answers1

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());
davidxxx
  • 125,838
  • 23
  • 214
  • 215